Pass a parent class as an argument?
在创建实例之前,是否可以不指定父类?例如这样的:
1 2 3 4 5 6 7 | class SomeParentClass: # something class Child(unspecifiedParentClass): # something instance = Child(SomeParentClass) |
这显然不起作用。但是否有可能这样做?
您可以在类"EDOCX1"〔1〕方法中更改实例的类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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() |
输出:
1 2 3 | initializing SomeParentClass instance initializing Child instance in SomeParentClass.hello() |
你试过这样的吗?
1 2 3 4 5 6 7 8 9 10 11 12 | class SomeParentClass(object): # ... pass def Child(parent): class Child(parent): # ... pass return Child() instance = Child(SomeParentClass) |
在python 2.x中,也要确保将
您可以在运行时动态更改基类。例如:
1 2 3 4 5 6 7 8 9 10 | 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) |
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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() |
结果:
1 2 | hello_1 hello_2 |
适用于python 2和3。
有关详细信息,请参阅相关问题"如何在运行时动态更改实例的基类"?