将父类作为参数传递?

Thr*_*asi 4 python inheritance arguments unspecified

在创建实例之前,是否可以不指定父类?
例如这样的事情:

class SomeParentClass:
    # something

class Child(unspecifiedParentClass):
    # something

instance = Child(SomeParentClass)
Run Code Online (Sandbox Code Playgroud)

这显然行不通。但是有可能以某种方式做到这一点吗?

mar*_*eau 5

您可以在类的__init__()方法中更改实例的类:

class Child(object):
    def __init__(self, baseclass):
        self.__class__ = type(self.__class__.__name__,
                              (baseclass, object),
                              dict(self.__class__.__dict__))
        super(self.__class__, self).__init__()
        print 'initializing Child instance'
        # continue with Child class' initialization...

class SomeParentClass(object):
    def __init__(self):
        print 'initializing SomeParentClass instance'
    def hello(self):
        print 'in SomeParentClass.hello()'

c = Child(SomeParentClass)
c.hello()
Run Code Online (Sandbox Code Playgroud)

输出:

class Child(object):
    def __init__(self, baseclass):
        self.__class__ = type(self.__class__.__name__,
                              (baseclass, object),
                              dict(self.__class__.__dict__))
        super(self.__class__, self).__init__()
        print 'initializing Child instance'
        # continue with Child class' initialization...

class SomeParentClass(object):
    def __init__(self):
        print 'initializing SomeParentClass instance'
    def hello(self):
        print 'in SomeParentClass.hello()'

c = Child(SomeParentClass)
c.hello()
Run Code Online (Sandbox Code Playgroud)


Let*_*rgy 2

你尝试过这样的事情吗?

class SomeParentClass(object):
    # ...
    pass

def Child(parent):
    class Child(parent):
        # ...
        pass

    return Child()

instance = Child(SomeParentClass)
Run Code Online (Sandbox Code Playgroud)

在Python 2.x中,也一定要包含object作为父类的超类,以使用新式类。