Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use super() to call the __init__ method of each base class in Python?

Let's suppose I have a bit of Python code:

class Mother:
    def __init__(self):
        print("Mother")

class Father:
    def __init__(self):
        print("Father")

class Daughter(Mother, Father):
    def __init__(self):
        print("Daughter")
        super().__init__()

d = Daughter()

This script prints "Daughter". Is there anyway to ensure that all of the __init__ methods of the bases classes are called? One method I came up with to do this was:

class Daughter(Mother, Father):
    def __init__(self):
        print("Daughter")
        for base in type(self).__bases__:
            base.__init__(self)

This script prints "Daughter", "Mother", "Father". Is there a nice way to do this using super() or another method?

like image 918
Giorgian Borca-Tasciuc Avatar asked Jun 29 '15 23:06

Giorgian Borca-Tasciuc


People also ask

What is the effect of calling super () __ Init__?

__init__() of the superclass ( Square ) will be called automatically. super() returns a delegate object to a parent class, so you call the method you want directly on it: super(). area() . Not only does this save us from having to rewrite the area calculations, but it also allows us to change the internal .

What does super () __ Init__ do in Python?

Understanding Python super() with __init__() methods When this method is called it allows the class to initialize the attributes of the class. In an inherited subclass, a parent class can be referred with the use of the super() function.

How do you call a method of super class in Python?

Using Super(): Python super() function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by 'super'.

How does super () work in Python?

The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.


1 Answers

Raymond Hettinger explained this really well in his talk Super Considered Super from PyCon 2015. The short answer is yes, if you design this way, and call super().__init__() in each class

class Mother:
    def __init__(self):
        super().__init__()
        print("Mother")

class Father:
    def __init__(self):
        super().__init__()
        print("Father")

class Daughter(Mother, Father):
    def __init__(self):
        super().__init__()
        print("Daughter")

The name super is unfortunate, it really works its way through the base classes.

like image 128
Ryan Haining Avatar answered Oct 12 '22 07:10

Ryan Haining