Python调用自己实例的构造函数
y应该是Bar类而不是Foo类Python调用自己实例的构造函数,python,Python,y应该是Bar类而不是Foo类 是否需要使用类似于:self.constructor()的东西来替代?对于新样式的类,使用type(self)来获取“当前”类: class Foo(): def __init__(self): pass def create_another(self): return Foo() # is not working as intended, because it will make y below b
是否需要使用类似于:
self.constructor()
的东西来替代?对于新样式的类,使用type(self)
来获取“当前”类:
class Foo():
def __init__(self):
pass
def create_another(self):
return Foo()
# is not working as intended, because it will make y below becomes Foo
class Bar(Foo):
pass
x = Bar()
y = x.create_another()
您也可以使用self.\uuuu class\uuu
,因为这是type()
将使用的值,但始终建议使用API方法
对于旧式类(python 2,不是从对象继承的)
,type()
没有多大帮助,因此您必须使用self
def create_another(self):
return type(self)()
@比利斯卡:除非你有充分的理由这么做,否则我会使用新型的类。让Foo
从对象继承。
def create_another(self):
return self.__class__()