/  Technology   /  Python super() with __init__() methods.

Python super() with __init__() methods.

Understanding Python super() with __init__() methods.

 

The “__init__” is a reserved method in python classes. It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class.

The super() function allows us to avoid using the base class name explicitly. In Python, the super() function is dynamically called as unlike other languages, as it is a dynamic language. The super() function returns an object that represents the parent class.

This function can be used to enable both Single and Multiple Inheritances.

 

super() in single Inheritance with __init__():

super() with Multiple Inheritance with __init__():

In a subclass, a parent class can be referred to using the super() function. It returns a temporary object of the superclass and this allows access to all of its methods to its child class. While using the super() keyword, we need not specify the parent class name to access its methods.

In the above program, we can see that only the first base class __init__() is getting called when we are using super().__init__().

To also call the second base class, we’ll have to add a new combination of super() and __init__() method. Look at the below example

super().__init__() calls the first base class init method.

super(State,self).__init__()  calls the second base class init method.

 

 

Leave a comment