Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python super() Function



ThePython super() function is abuilt-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, thesuper() will always refer to the correct superclass without any modifications needed in the subclass.

Syntax

Following is the syntax of the Pythonsuper() function −

super()

Parameters

The Pythonsuper() 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 ofsuper() function in Python:

Example: Use of super() Function

The following example practically demonstrates the usage of Pythonsuper() 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 = orgNameclass Employee(Company):   def __init__(self, orgName, empName):      super().__init__(orgName)      self.empName = empNameemployee = 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

Thesuper() function can be used tooverride 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 withsuper() in MultipleInheritance.

class Organisation:   def __init__(self, orgName):      self.orgName = orgNameclass Hr(Organisation):   def __init__(self, orgName, hrName):      super().__init__(orgName)      self.hrName = hrNameclass Employee(Hr):   def __init__(self, orgName, hrName, empName):      super().__init__(orgName, hrName)      self.empName = empNameemp = 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: TutorialsPointHR Name: K. RajaEmployee Name: Shrey
python_built_in_functions.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp