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

Api*_*bul 9 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()
Run Code Online (Sandbox Code Playgroud)

你应该是Bar not Foo.

是否有类似的东西self.constructor()

Mar*_*ers 26

对于新式类,用于type(self)获取"当前"类:

def create_another(self):
    return type(self)()
Run Code Online (Sandbox Code Playgroud)

您也可以使用self.__class__该值type(),但始终建议使用API​​方法.

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

def create_another(self):
    return self.__class__()
Run Code Online (Sandbox Code Playgroud)

  • @Billiska:除非你有充分的理由这样做,否则我会使用新式的课程.让`Foo`继承自`object`. (2认同)