Python’s super() Function

Learn Python @ Freshers.in

In Python, the super() function is a powerful tool for accessing methods and properties of parent classes in inheritance. This article aims to elucidate its usage, applications, and significance through comprehensive examples.

Understanding super() Function

The super() function in Python is utilized to access methods and properties of the parent class in inheritance. Its syntax is straightforward:

super().__init__()

Here, super() is used within the child class to call the constructor of the parent class.

Example 1: Accessing Parent Class Method

class Parent:
    def show(self):
        print("Parent class method")
class Child(Parent):
    def display(self):
        super().show()
child_obj = Child()
child_obj.display()

Output 1:

Parent class method

Example 2: Using super() with init()

class Parent:
    def __init__(self, name):
        self.name = name

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age

child_obj = Child("John", 30)
print("Name:", child_obj.name)
print("Age:", child_obj.age)

Output 2:

Name: John
Age: 30

Example 3: Multiple Inheritance with super()

class Parent1:
    def show(self):
        print("Parent1 class method")

class Parent2:
    def display(self):
        print("Parent2 class method")

class Child(Parent1, Parent2):
    def demonstrate(self):
        super().show()
        super().display()

child_obj = Child()
child_obj.demonstrate()

Output 3:

Parent1 class method
Parent2 class method

Points to Remember

  • The super() function is used to access methods and properties of the parent class in inheritance.
  • It allows for cooperative method calls in multiple inheritance scenarios.
  • super() is typically used within the child class to call methods or constructors of the parent class.
Author: user