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

The Python super() function returns returns an object representing the parent class.

Examples

In this section, we will see some examples of super() function −

Example 1

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 2

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 3

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
python_built_in_functions.htm
Advertisements