Super Function in Python Programming | Python Programming
Super Function: Super Function in python programming is the built in function used to access the parent class member form the child class having same member name or method name. Let’s make it more clear by below example:
#Super function example class A: def __init__(self): print("Parent class Constructor") class B(A): def __init__(self): print("Child class Constructor") obj = B()
#Output # Child class Constructor
In above example, our output is “Child class Constructor”. But point to note is that our child class also inheriting the properties of parent class A, but why he did not returned the parent class constructor as output? Why it returned their own constructor.
This is because, In that case if any class already have their own member (variable, method or constructor) available, then its first priority is to return their own. If they do not have their own, then it prefer to return the inherited property.
Important: We use super() function , if we want to access the parent class member from child class explicitly. Please follow below given example.
Example 1: Example to elaborate the use of Super function
#Super function example class A: x = "Parent class variable" def __init__(self): print("Parent class Constructor") def fun1(self): print("Parent class method") class B(A): x= "Child class variable" def fun1(self): print("Child class method") def __init__(self): print("Child class Constructor") super().__init__() #calling parent class Constructor print(super().x) #calling parent class variable super().fun1() #parent class method called obj = B()
#Output # Child class Constructor # Parent class Constructor # Parent class variable # Parent class method