我有一个类父类和两个子类 child1(parent) 和 child2(parent) 有点像下面的近代码。(编辑以更正确地显示父类正在做某事)
class parent(object):
name = None
def __init__(self,e):
# process the common attributes
name = e.attrib['name']
def __new__(cls,e):
if e.attrib['type'] == 'c1':
return child1(e)
elif e.attrib['type'] == 'c2':
return child2(e)
else:
raise
class child1(parent):
extra1 = None
def __init__(self,e):
super(e)
# set attributes from e that are specific to type c1
class child2(parent):
extra2 = None
def __init__(self,e):
super(e)
# set attributes from e that are specific to type c2
目标是能够根据参数的值获得“正确”的类。因此,如果我可以说obj = parent(element)
并且obj
将是child1
或者child2
取决于值element.attrib['type']
是什么。