有没有办法根据传递的变量动态更改对象类?例如:
class Parent:
def __init__(self, variable):
...
some magic
...
class ChildA:
pass
class ChildB:
pass
cls=Parent('a')
cls.__class__
<class '__main__.ChildA'>
cls=Parent('b')
cls.__class__
<class '__main__.ChildB'>
答案 0 :(得分:1)
这可以在Parent类的__new__
方法中完成。它可以决定实际创建的对象:
class Parent(object):
def __new__(cls, selector):
if selector == 'a':
return object.__new__(A)
else:
return object.__new__(B)
class A(Parent):
letters = 'aaaaa'
class B(Parent):
letters = 'bbbbb'
a = Parent('a')
print(a.letters)
b = Parent('b')
print(b.letters)
输出证明它有效:
aaaaa
bbbbb
答案 1 :(得分:0)
在__new__
之前的父级的__init__
函数中定义条件检查if。
class Parent(Object):
def __new__(self,s):
if s=='a':
return object.__new__(childA)
else:
return object.__new__(childB)
class childA(Parent):
pass
class childB(Parent):
pass