Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain-calling parent initialisers in python [duplicate]

People also ask

How do you call a parent constructor in Python?

Use super(). __init()__ to call the immediate parent class constructor in Python. Calling a parent constructor within a child class executes the operations of the parent class constructor in the child class.

Does Python automatically call parent constructor?

Answer. No, an inherited class is not required to call the __init__() method of the parent class. If no __init__() method is implemented in the inherited class, then the parent __init__() will be called automatically when an object of the inherited class is created.

What is constructor chaining in Python?

Constructor chaining is the process of calling one constructor from another constructor. Constructor chaining is useful when you want to invoke multiple constructors, one after another, by initializing only one instance. In Python, constructor chaining is convenient when we are dealing with inheritance.

How do I call a super constructor in Python?

Use __init()__ on super() inside the constructor of the subclass to invoke the constructor of the superclass in Python. In inheritance invoking the super constructor of a subclass invokes the constructor of its superclass.


Python 3 includes an improved super() which allows use like this:

super().__init__(args)

The way you are doing it is indeed the recommended one (for Python 2.x).

The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".


You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"