Python调用自己实例的构造函数

时间:2013-01-08 06:51:11

标签: python

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()

y应该是Bar not Foo。

是否可以使用self.constructor()来代替?

1 个答案:

答案 0 :(得分:25)

对于新式课程,请使用type(self)获取“当前”课程:

def create_another(self):
    return type(self)()

您也可以使用self.__class__因为type()将使用的值,但始终建议使用API​​方法。

对于旧式类(python 2,不是从object继承),type()没有那么有用,所以你被迫使用self.__class__

def create_another(self):
    return self.__class__()