Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python call constructor of its own instance

Tags:

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

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

like image 532
Apiwat Chantawibul Avatar asked Jan 08 '13 06:01

Apiwat Chantawibul


People also ask

How do you call a self constructor in Python?

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

How do you call a constructor from a parent class in Python?

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 .

How do you call a constructor from another class in Python?

We can use the super() function to call the superclass constructor function. We can also use the superclass name to call its init() method.

Can we call constructor manually in Python?

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.


1 Answers

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__()
like image 120
Martijn Pieters Avatar answered Oct 21 '22 08:10

Martijn Pieters