0

I understand that If super().__init__() is in a Python child class, it inherits the attributes of the parent class. I was just wondering what if we call super().__init__() in the parent class itself as shown below:

class Base:
    def __init__(self,*args,**kwrgs):
        super.__init__(args, kwrgs)

What is the use of calling a super in the parent class?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

7

For a simple example as in your question, indeed it makes no point. It will simply call object.__init__ which doesn't do much and takes no arguments.

BUT, it makes a difference with multiple inheritance. For example, the following code:

class Base:
    def __init__(self, *args, **kwrgs):
        super().__init__(*args, **kwrgs)
        print("in Base")

class SecondBase:
    def __init__(self, *args, **kwrgs):
        super().__init__(*args, **kwrgs)
        print("in SecondBase")

class A(Base, SecondBase):
    def __init__(self, *args, **kwrgs):
        super().__init__(*args, **kwrgs)
        print("in A")

class B(SecondBase, Base):
    def __init__(self, *args, **kwrgs):
        super().__init__(*args, **kwrgs)
        print("in B")

print("A:")
A()
print("B:")
B()

Will produce:

A:
in SecondBase
in Base
in A
B:
in Base
in SecondBase
in B

As you can see, both Base and SecondBase are what you would call base classes, i.e. not inheriting. Still, because of A and B's multiple inheritance, the super() calls return either Base/SecondBase respectively or object, depending on the MRO. This can be seen as:

>>> A.mro()
[<class '__main__.A'>, <class '__main__.Base'>, <class '__main__.SecondBase'>, <class 'object'>]

>>> B.mro()
[<class '__main__.B'>, <class '__main__.SecondBase'>, <class '__main__.Base'>, <class 'object'>]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • as understand the mro set the order of the classes parent initialization , in ur example it confusing cause it work in the exact opposite order , for A() the order is first Base but actually we see the prints coming from SecondBase – AviC May 07 '22 at 08:48
  • @AviC that just happens because the prints are after the `super` calls. So first we go down all the way in the MRO and then print as we go up. This is why the prints seem to be in reverse order. The order of `super` calls matches exactly the MRO – Tomerikoo May 11 '22 at 17:21