Python super() keyword
Introduction
In Python, the super() keyword is a built-in method that returns a proxy object (object of a superclass that is temporary). It allows us to access methods present in the base class.
Uses of super()
In Python, the super() keyword has two major uses:
- It allows us to avoid using the name of the base class explicitly.
- Works with multiple inheritances.
Example 1
Code
Output
Example 2: super() with Single Inheritance
Code
Output
Example 3:super() with Multiple Inheritance
Code
Output
In the above code, we called the init(0 function of the ml class (from the Dog class) using code
instead of
We can change the name of the base class easily because we do not have to mention the name of the base class when we call its members.
The super() is a built python method that returns a proxy object, and it is a substitute object that can invoke the base class’s members using delegation. This is indirection, i.e. ability to reference the base class with super()).
Since it is computed at runtime, we can use different base classes at different times.
Method Resolution Order (MRO)
MRO (Method Resolution Order) is an order. In this order, the method should b in the existence of multiple inheritances. MRO can also be viewed by using the mro attribute.
Working of MRO
- Before the calling of the base class, the method in the derived call is called always.
- In the example above, we called the Dog class before NonMArineml, which is also invoked before al, and the al class is also invoked before the object.
- If there exist multiple parents such as Dog(Nonmarineml, NonWingedml) because NonMarineml appears first that is why it is also invoked first.