super() Function in Python

Python super() Function

In Python, the super() function is used to call a method from the parent class (superclass) in the context of a subclass. It is commonly used in inheritance to access and invoke methods or attributes defined in the parent class.

The primary purpose of using super() is to ensure that the method resolution order (MRO) is followed correctly when multiple inheritance is involved. The MRO determines the sequence in which Python looks for a method in a class hierarchy. By using super(), you can avoid explicitly referring to the parent class and allow Python to handle the method resolution correctly.

The super() function is often used inside the __init__() method of a subclass to initialize the attributes defined in the parent class, but it can also be used in other methods as needed.

Here's the basic syntax of using super():

class SubClassName(ParentClassName):
    def __init__(self, args, kwargs):
        super().__init__(args, kwargs)  # Calls the __init__() method of the parent class
        # Additional initialization code for the subclass

Example usage:

class Animal:
    def __init__(self, species):
        self.species = species

    def make_sound(self, sound):
        print(f"{self.species} makes {sound} sound.")


class Dog(Animal):
    def __init__(self, breed, name):
        super().__init__("Dog")  # Call the __init__() of the parent class
        self.breed = breed
        self.name = name

    def bark(self):
        print("Woof! Woof!")


# Creating an instance of the Dog class
my_dog = Dog("Labrador", "Buddy")
my_dog.make_sound("bark")  # Output: Dog makes bark sound.
my_dog.bark()  # Output: Woof! Woof!

In the example above, Dog is a subclass of Animal. By using super().__init__() inside the __init__() method of Dog, we ensure that the __init__() method of the Animal class is executed first, and the species attribute is initialized before adding the additional attributes (breed and name) specific to the Dog class.

It's important to note that super() is used with new-style classes, which means the classes should inherit from object or another new-style class explicitly (e.g., class Dog(Animal, object) or class Dog(Animal) where Animal is a new-style class). In Python 3, all classes are new-style classes by default. However, in Python 2, you need to explicitly inherit from object to use super() properly.