传递父类作为参数?

时间:2013-09-08 11:24:18

标签: python inheritance arguments unspecified

在创建实例之前是否可以不指定父类? 例如像这样的东西:

class SomeParentClass:
    # something

class Child(unspecifiedParentClass):
    # something

instance = Child(SomeParentClass)

这显然不起作用。但是有可能以某种方式这样做吗?

3 个答案:

答案 0 :(得分:3)

您可以在类“__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()

答案 1 :(得分:2)

你尝试过这样的事吗?

class SomeParentClass(object):
    # ...
    pass

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

    return Child()

instance = Child(SomeParentClass)

在Python 2.x中,还要确保包含object作为父类的超类,以使用新式类。

答案 2 :(得分: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中都运行良好。

有关详细信息,请参阅相关问题How to dynamically change base class of instances at runtime?