5

Is it possible to leave a parent class unspecified until an instance is created?
e.g. something like this:

class SomeParentClass:
    # something

class Child(unspecifiedParentClass):
    # something

instance = Child(SomeParentClass)

This obviously does not work. But is it possible to do this somehow?

4

3 回答 3

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()

输出:

initializing SomeParentClass instance
initializing Child instance
in SomeParentClass.hello()
于 2013-09-08T14:13:15.030 回答
2

你有没有尝试过这样的事情?

class SomeParentClass(object):
    # ...
    pass

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

    return Child()

instance = Child(SomeParentClass)

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

于 2013-09-08T12:19:38.377 回答
0

您可以在运行时动态更改基类。如:

class SomeParentClass:
    # something

class Child():
    # something

def change_base_clase(base_class):
    return type('Child', (base_class, object), dict(Child.__dict__))()

instance = change_base_clase(SomeParentClass)

例如:

class Base_1:
    def hello(self):
        print('hello_1')

class Base_2:
    def hello(self):
        print('hello_2')

class Child:pass

def add_base(base):
    return type('Child', (base, object), dict(Child.__dict__))()

# if you want change the Child class, just:
def change_base(base):
    global Child
    Child = type('Child', (base, object), dict(Child.__dict__))

def main():
    c1 = add_base(Base_1)
    c2 = add_base(Base_2)
    c1.hello()
    c2.hello()

main()

结果:

hello_1
hello_2

在 python 2 和 3 中运行良好。

有关更多信息,请参阅相关问题如何在运行时动态更改实例的基类?

于 2013-09-08T13:28:31.570 回答