How to invoke the super constructor in Python
In this tutorial, we are going to learn how to invoke the super constructor in Python.
Let’s start with the basics of Inheritance.
Certainly, anyone who is used with OOP will have some knowledge about core concepts.
Basically, Inheritance is defined as the technique to make a new class from the previous or parent class.
How Inheritance Works in Python:
class A: # A is parent class def __init__(self,data): self.data=data def fly(self): print("Yes A can fly") class B(A): # B is child class def __init__(self,s): self.s=s b = B("hi") # object of child class b.fly()
Output : Yes A can fly
If it seems difficult to understand the code the following points will help,
- A is a parent class that has a method named fly( ).
- B is a child class or derived class which inherits all the methods of class A.
- When an object of class B is created and invoked with a method fly then the fly( ) method of A gets executed.
- This is basically done by the Method resolution order.
Method Resolution Order :
In object-oriented programming when a function or a method is called there is a particular order in which the control checks if the method exists or not.
For the above example, the order looks like this.
| Method resolution order: | B | A | builtins.object
As the method fly( ) was absent in class B, the method fly( ) in class A got executed according to the above order.
Invoking of super constructor in Python and the need to do so:
Certainly, if the fly method is present in class B that particular method would get executed.
Let’s have a look at this.
class A: def __init__(self,data): self.data=data def fly(self): print("Yes A can fly") class B(A): def __init__(self,s): self.s=s def fly(self): # fly method is present in class B now print("Yes B can fly") b = B("hi") b.fly() # INVOKING fly with object of class B
Output : Yes B can fly
There should be no problem until now, as the output clearly resembles the order discussed above.
Certainly, Now the main question is why super constructor?
Because, if we want to invoke the method fly( ) of the parent class using the object of a child class.
That is the time when we need the super constructor.
Moreover, this example should clarify all the doubts if any.
class A: def __init__(self,data): self.data=data def fly(self): print("Yes A can fly") class B(A): def __init__(self,s): self.s=s def fly(self): print("Yes B can fly") super().fly() # invoking super constructor and that invokes parent class fly() method b = B("hi") b.fly()
Output : Yes B can fly Yes A can fly
Concluding, there are two things to be learned from this example,
- the super constructor is invoked by syntax super(). method_name
- It is used to call the parent class method from the child class itself.
You may also learn: Underscore Methods in Python
Leave a Reply