Python call constructor of its own instance

后端 未结 1 1417
逝去的感伤
逝去的感伤 2021-02-13 21:28
class Foo():
    def __init__(self):
        pass
    def create_another(self):
        return Foo()
        # is not working as intended, because it will make y below b         


        
相关标签:
1条回答
  • 2021-02-13 22:05

    For new-style classes, use type(self) to get the 'current' class:

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

    You could also use self.__class__ as that is the value type() will use, but using the API method is always recommended.

    For old-style classes (python 2, not inheriting from object), type() is not so helpful, so you are forced to use self.__class__:

    def create_another(self):
        return self.__class__()
    
    0 讨论(0)
提交回复
热议问题