super() Method in Python

Published Sept. 7, 2023, 12:37 p.m.

Definition: In Python, the super() method is a built-in feature used to facilitate inheritance and maintain a clear and organized structure in object-oriented programming. It allows a subclass to access and invoke methods and constructors defined in its parent or superclass.

How to Use super():

You can utilize super() in two primary ways:

  1. Inside a Subclass Constructor: To invoke the constructor of the parent class, use super().__init__() within the constructor of the child class. This is particularly useful for initializing attributes inherited from the parent class.

  2. Inside a Subclass Method: To call a method from the parent class, employ super().method_name() within a method of the child class. This empowers you to reuse or extend functionality defined in the parent class's methods.

Why Use super():

  • Code Reusabilitysuper() promotes the reuse of code, ensuring that you don't duplicate logic that already exists in the parent class. It helps maintain a DRY (Don't Repeat Yourself) codebase.

  • Polymorphism: It enables method overriding in the child class while still allowing access to the parent class's method when necessary. This supports polymorphism, where objects of different classes can respond to the same method call in a class-specific way.

  • Initialization: In many cases, when inheriting from a parent class, you need to initialize attributes inherited from the parent. super() streamlines this process by letting you invoke the parent class's constructor and then add any child-class-specific initialization.

Where to Use super():

You should incorporate super() in scenarios involving class inheritance, especially when:

  1. Overriding Methods: You wish to override a method from the parent class in the child class but still want to execute the parent's method logic.

  2. Initialization: You need to initialize attributes inherited from the parent class while introducing new attributes or behaviors in the child class.

  3. Polymorphism: You intend to leverage polymorphism, allowing different objects (instances of child classes) to respond to the same method call in a way that suits their specific class.

  4. Calling Class Methods: You want to invoke class methods or access class attributes from the parent class within the child class.

  5. Maintaining Inheritance Hierarchy: To ensure the parent class's code is executed when necessary, ensuring a well-defined and organized inheritance hierarchy.

Example:

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

    def speak(self):
        print(f"{self.name} makes a sound")

# Child class inheriting from Animal
class Dog(Animal):
    def speak(self):
        super().speak()  # Calling parent's speak method
        print(f"{self.name} barks")

# Creating instances
animal = Animal("Generic Animal")
dog = Dog("Buddy")

animal.speak()  # Output: Generic Animal makes a sound
dog.speak()  # Output: Buddy makes a sound, Buddy barks

In this example, super() is used to call the parent class's speak() method from the child class, demonstrating method overriding and code reuse.


🚀 Super() Method in Python

Super() is like a magical bridge that connects child and parent classes in Python! 🌉

Demo Program 1:

# Let's create a Person class
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display(self):
        print('Name:', self.name)
        print('Age:', self.age)

# Now, a Student class that inherits from Person
class Student(Person):
    def __init__(self, name, age, rollno, marks):
        super().__init__(name, age)  # Calling the parent's constructor
        self.rollno = rollno
        self.marks = marks

    def display(self):
        super().display()  # Calling the parent's display method
        print('Roll No:', self.rollno)
        print('Marks:', self.marks)

s1 = Student('Jai', 22, 101, 90)
s1.display()  # Output will show Jai's info

🔍 Explanation:

In this program, we have two classes: Person and StudentStudent is a child of Person. We use super() to call the constructor and display() method of the parent class (Person) from the child class (Student).

Demo Program 2:

# Parent class with class variables and methods
class P:
    a = 10

    def __init__(self):
        self.b = 10

    def m1(self):
        print('Parent instance method')

    @classmethod
    def m2(cls):
        print('Parent class method')

    @staticmethod
    def m3():
        print('Parent static method')

# Child class inheriting from P
class C(P):
    a = 888

    def __init__(self):
        super().__init__()  # Calling the parent's constructor
        print(super().a)  # Accessing parent's class variable a
        super().m1()  # Calling parent's instance method
        super().m2()  # Calling parent's class method
        super().m3()  # Calling parent's static method

c = C()  # Creating an instance of the child class

🔍 Explanation:

In this program, we have a parent class P and a child class C. We use super() to access and call various members (variables and methods) of the parent class (P) from the child class (C).

Calling Methods of a Particular Super Class:

You can call methods from a specific superclass using super() in two ways:

  1. super(D, self).m1(): Calls the m1() method of the superclass of D.

  2. A.m1(self): Calls the m1() method of class A.

Here's an example:

class A:
    def m1(self):
        print('A class Method')

class B(A):
    def m1(self):
        print('B class Method')

class C(B):
    def m1(self):
        print('C class Method')
        A.m1(self)  # Calling method_a from class A

# Creating an instance of class C
c_instance = C()
c_instance.m1()  # Output: C class Method, A class Method

🌟 Super() Tips:

  • In general, use self to access parent class instance variables from the child class.

  • You can access parent class static variables using super().

  • From child class constructors and instance methods, you can use super() to access parent class instance methods, static methods, and class methods.

  • In child class class methods, you cannot directly access parent class instance methods and constructors using super(), but you can do it indirectly.

  • Avoid using super() in child class static methods, but if needed, you can call parent class static methods with super(B, B).method_name().