如何从层次结构中创建 class 即 returns 和 child?
How to make a class that returns a child from the hierarchy?
我正在尝试让 class 找到初始化它的 object 的类型,我希望它成为 object class对应于发送的 object 'typ' 的类型。
因此,如果要执行类似于以下示例的操作,我希望变量 'this' 成为 TypeA 的实例。
怎么办?
class Master():
def __init__(self, typ):
if typ == 'a':
return TypeA()
else:
return TypeB()
def TypeA():
def __init__(self):
pass
def boop():
print "type A"
def TypeB():
def __init__(self):
pass
def meep():
print "type B"
this = Master('a')
this.boop()
(如果这对任何人都有意义,我想模拟 PyMel 在您使用 pm.PyNode('object_name') 创建 object 时的行为,其中 pm.PyNode 为您提供层次结构中最低的 child。)
看来你想要一个工厂。也许是这些行中的一些东西:
class Master(object): # i would rather do a plain function but i'll limit to mimic your lines.
@staticmethod
def factory(typ, *args, **kwargs):
mapping = {
'a': TypeA,
'b': TypeB
}
return mapping[typ](*args, **kwargs)
那么你可以这样称呼它:
this = Master.factory('a')
print this
$ <__main__.TypeA object at 0x7f6cbbec65d0>
我正在尝试让 class 找到初始化它的 object 的类型,我希望它成为 object class对应于发送的 object 'typ' 的类型。
因此,如果要执行类似于以下示例的操作,我希望变量 'this' 成为 TypeA 的实例。
怎么办?
class Master():
def __init__(self, typ):
if typ == 'a':
return TypeA()
else:
return TypeB()
def TypeA():
def __init__(self):
pass
def boop():
print "type A"
def TypeB():
def __init__(self):
pass
def meep():
print "type B"
this = Master('a')
this.boop()
(如果这对任何人都有意义,我想模拟 PyMel 在您使用 pm.PyNode('object_name') 创建 object 时的行为,其中 pm.PyNode 为您提供层次结构中最低的 child。)
看来你想要一个工厂。也许是这些行中的一些东西:
class Master(object): # i would rather do a plain function but i'll limit to mimic your lines.
@staticmethod
def factory(typ, *args, **kwargs):
mapping = {
'a': TypeA,
'b': TypeB
}
return mapping[typ](*args, **kwargs)
那么你可以这样称呼它:
this = Master.factory('a')
print this
$ <__main__.TypeA object at 0x7f6cbbec65d0>