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?
You could also use self. __class__ as that is the value type() will use, but using the API method is always recommended.
Use super(). __init__() to call the immediate parent class constructor. Call super(). __init__(args) within the child class to call the constructor of the immediate parent class with the arguments args .
We can use the super() function to call the superclass constructor function. We can also use the superclass name to call its init() method.
Bookmark this question. Show activity on this post. This Question / Answer (Python call constructor in a member function) says it is possible to to call the constructor from within a member function.
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__()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With