Apiwat Chantawibul
Apiwat Chantawibul

Reputation: 1463

Python call constructor of its own instance

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 should be of class Bar not Foo.

Is there something like: self.constructor() to use instead?

Upvotes: 23

Views: 16166

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121346

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

Upvotes: 44

Related Questions