Python super() Function
The Python super() function is a built-in function that allows us to call methods or properties of a superclass in a subclass. It is not required to mention the name of the parent class to access the methods present in it.
One benefit of using this function is that even if the inheritance hierarchy changes, the super() will always refer to the correct superclass without any modifications needed in the subclass.
Syntax
Following is the syntax of the Python super() function −
super()
Parameters
The Python super() function does not accept any parameters.
Return Value
This function returns returns an object representing the parent class.
super() Function Examples
Practice the following examples to understand the use of super() function in Python:
Example: Use of super() Function
The following example practically demonstrates the usage of Python super() function. Here, we are defining single level inheritance and trying to call the __init__ method of the Parent class.
class Company:
def __init__(self, orgName):
self.orgName = orgName
class Employee(Company):
def __init__(self, orgName, empName):
super().__init__(orgName)
self.empName = empName
employee = Employee("TutorialsPoint", "Shrey")
print("Accessing parent class properties:")
print(employee.orgName)
When we run above program, it produces following result −
Accessing parent class properties: TutorialsPoint
Example: Override Parents Class Method Using super() Function
The super() function can be used to override any method of the parent class as illustrated in the below code. Here, we are overriding the method named "newMsg".
class Message:
def newMsg(self):
print("Welcome to Tutorialspoint!!")
class SendMsg(Message):
def newMsg(self):
print("You are on Tutorialspoint!!")
super().newMsg()
sendMsg = SendMsg()
print("Overriding parent class method:")
sendMsg.newMsg()
Following is an output of the above code −
Overriding parent class method: You are on Tutorialspoint!! Welcome to Tutorialspoint!!
Example: Use of super() Function in Multiple Inheritance
The code below demonstrates how to access parent class with super() in Multiple Inheritance.
class Organisation:
def __init__(self, orgName):
self.orgName = orgName
class Hr(Organisation):
def __init__(self, orgName, hrName):
super().__init__(orgName)
self.hrName = hrName
class Employee(Hr):
def __init__(self, orgName, hrName, empName):
super().__init__(orgName, hrName)
self.empName = empName
emp = Employee("TutorialsPoint", "K. Raja", "Shrey")
print(f"Organisation Name: {emp.orgName}")
print(f"HR Name: {emp.hrName}")
print(f"Employee Name: {emp.empName}")
Output of the above code is as follows −
Organisation Name: TutorialsPoint HR Name: K. Raja Employee Name: Shrey