You are currently viewing What is Super Function In Python

What is Super Function In Python

  • Post author:
  • Post category:Python
  • Post comments:0 Comments
  • Reading time:7 mins read

In Python, the super() function is a built-in function that plays an important role in object-oriented programming (OOP). It is used to call methods from a parent or superclass in the context of class inheritance. Understanding super() is key to mastering inheritance and method resolution in Python, which enables you to write cleaner and more maintainable code. This function facilitates calling the parent class’s methods without needing to explicitly name the class. Additionally, it helps in managing the complexity of multiple inheritance by resolving method conflicts in a controlled manner.

Purpose and Syntax

The primary purpose of super() is to allow access to methods in a superclass from a subclass, especially when these methods have been overridden in the subclass. This is particularly useful when you want to extend or modify the behavior of a parent class method rather than completely replacing it. The syntax of super() is:

python

Copy code

super().method_name()

Here, super() returns a temporary object of the superclass that allows you to call its methods. The method_name() part refers to the specific method you want to call from the parent class.

Python

Basic Example: Single Inheritance

In single inheritance, where a subclass inherits from a single superclass, the super() function can be used to invoke methods from the parent class. Here’s a basic example:

python

Copy code

class Animal:

    def speak(self):

        print(“Animal speaks”)

class Dog(Animal):

    def speak(self):

        super().speak()  # Call the speak method from the parent class

        print(“Dog barks”)

dog = Dog()

dog.speak()

Output:

Copy code

Animal speaks

Dog barks

In this example:

  • The Dog class inherits from Animal and overrides the speak method.
  • The super().speak() call inside the Dog class invokes the speak method from the Animal class, ensuring that the base functionality is executed before the subclass-specific functionality (printing “Dog barks”).

Why Use super()?

The main reason to use super() is to avoid explicitly referring to the parent class in a subclass. This promotes better code maintainability and makes it easier to change the class hierarchy later, as you don’t have to modify the method calls inside subclasses. Here are some reasons to use super():

  1. Avoiding Redundancy: If the parent class already implements a method, calling super() avoids rewriting that method in every subclass that inherits from it.
  2. Code Reusability: By using super(), you can reuse the functionality of the parent class, modifying it if necessary, without fully overriding it.
  3. Consistency: It allows subclasses to consistently use and extend the behavior of the parent class, which can make code more predictable.
super function in python

Example: Multiple Inheritance

Python supports multiple inheritance, which means a class can inherit from more than one superclass.This can lead to complexities, especially when multiple parent classes have methods with the same name. The super() function, in conjunction with Python’s method resolution order (MRO), helps resolve such conflicts. The MRO determines the order in which base classes are considered when searching for a method.

Consider the following example using multiple inheritance:

python

Copy code

class A:

    def greet(self):

        print(“Hello from class A”)

class B:

    def greet(self):

        print(“Hello from class B”)

class C(A, B):

    def greet(self):

        super().greet()  # Calls the greet method from class A, as it’s first in the MRO

        print(“Hello from class C”)

obj = C()

obj.greet()

Output:

javascript

Copy code

Hello from class A

Hello from class C

In this case:

  • Class C inherits from both A and B.
  • super().greet() calls the greet method from class A, because A is listed first in the method resolution order (MRO). If class B were listed first, it would be called instead.
  • The MRO is automatically determined by Python, but you can inspect it using C.__mro__ or C.mro().

The Method Resolution Order (MRO)

The method resolution order (MRO) determines the sequence in which base classes are searched for a method.This order is important in the case of multiple inheritance. Python uses the C3 linearization algorithm to determine the MRO, ensuring that the method search is done in a consistent and predictable order.

To check the MRO of a class, you can use the mro() method:

python

Copy code

print(C.mro())

This will output something like:

python

Copy code

[<class ‘__main__.C’>, <class ‘__main__.A’>, <class ‘__main__.B’>, <class ‘object’>]

The MRO ensures that each class appears only once, and the search for a method is done in the correct order, following the inheritance chain.

Python in super function

Multiple Inheritance and super()

In multiple inheritance, super() is particularly useful to avoid explicitly calling methods from each parent class, which would otherwise lead to redundancy. Python ensures that the super() function always calls methods according to the MRO, avoiding the “diamond problem,” where a method is called multiple times due to inheritance from more than one class.

super() in Python 2 vs Python 3

In Python 2, super() requires the class and instance to be explicitly provided:

python

Copy code

super(CurrentClass, self).method_name()

However, in Python 3, you no longer need to specify the class and instance explicitly; you can just call super().method_name() as shown in the examples.

Conclusion

The super() function is a powerful tool in Python for working with inheritance. It allows subclasses to call methods from their parent classes in a way that promotes reusability, flexibility, and maintainability of code. In cases of single inheritance, it allows you to extend the functionality of the base class, and in multiple inheritance, it helps manage the complexity of method resolution by adhering to the method resolution order (MRO). By using super(), you can write cleaner, more efficient code that’s easier to maintain and extend.

Leave a Reply