Methods and Functions

Python super()

The Python super() function is used to return a temporary object of the parent class that also allows us access to its methods in the child class. Python super() is a built-in function that is used to gain access to a parent or sibling class’s methods and properties.

Python super() function is applicable to the concept of Inheritance. Before understanding what the Python super() built-in function does, let us understand Inheritance.

Inheritance

In Python, Inheritance refers to the method through which a new class uses code from an existing class to construct its structure. It is one of Python’s most essential OOP features. Inheritance occurs when a class inherits some or all of the behaviors and attributes of another class. The class from which other classes are being inherited is called the super-class/parent class/base class. While the classes which are inherited are called as sub-class/child classes. We can think of it as a child inheriting characteristics from its parents.

python super

Python super()

To make inheritance more flexible, manageable and extensible Python provides a built-in function called as super(). The super() function in Python allows you to access methods in a parent class. Using super() to call previously built methods saves you from rebuilding and recoding those methods in your subclass and allowing you to swap out super-classes with minimal code modifications.

The super() function has two primary applications:

  1. To avoid explicitly using the super (parent) class.
  2. To allow working with multiple inheritances.

Syntax of Python super

The syntax is as follows:

Note – There are no arguments accepted by the super() function. Succeeding the Python super() function, you indicate the method you want to inherit in that child/sub-class.

Example

                    

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

class Child(Parent):   # Child class inheriting Parent class
    def __init__(self, msg):
        super().__init__(msg)   # inherits Parent class function __init__   

x = Child('Tom Hanks')

Output

The above Child class inherits the values from the Parent class __init__ method. Here, we have used the super() function preceding the __init__ function which we wanted to inherit in the child class from the parent class. And therefore when we pass values to the Child class, it utilizes the code from the Parent __init__ method and prints the name.

Benefits of super python

Let us look at a few benefits which Python super() function offers us:

  • It is not necessary to know or specify the parent class name in order to access its functions.
  • Python super() function is applicable to both single and multiple inheritances.
  • Because there is no need to rewrite the complete function again, this implements flexibility, modularity, and code reusability.
  • Because Python, unlike other languages, is a dynamic language, super functions are called dynamically.

Example 1: super() with Single Inheritance

Single Inheritance is a case where a Child class is derived/inherited from a single Parent class.

Example

                    

class Vehicle:   # Parent class
    def __init__(self, v_type, purpose, engine, avg):
        self.v_type = v_type
        self.purpose = purpose
        self.engine = engine
        self.avg = avg

class FourWheeler(Vehicle):   # Child class inheriting Parent class
    def __init__(self, v_type, purpose, engine, avg):
        super().__init__(v_type, purpose, engine, avg)   # inherits Parent class function __init__     

x = FourWheeler('Car', 'Private use', '1500 cc', '19 kmph')

print('Type of 4-Wheeler:', x.v_type)
print('Purpose of 4-Wheeler:', x.purpose)
print('Engine cc:', x.engine)
print('Average:', x.avg)

Output

                    

Type of 4-Wheeler: Car
Purpose of 4-Wheeler: Private use
Engine cc: 1500 cc
Average: 19 kmph

Explanation

Vehicle is a super/parent class in the above example, whereas FourWheeler is a derived/child type. The child class can access the parent class’s __init__() property by using the super keyword. In other words, super() enables you to create classes that quickly enhance the capabilities of previously created classes without having to re-implement their functionality.

Example 2: python super multiple inheritance

Multiple Inheritance is an instance where a child class has been inherited from more than 1 parent class.

Example

                    

class Vehicle:
    def __init__(self, vehicle):
        print(vehicle, 'is a type of Vehicle.')

class Car(Vehicle):
    def __init__(self, cartype):
        print(cartype, 'is a Car')
        super().__init__(cartype)

class CityRide(Car):
    def __init__(self, cityride):
        print(cityride, 'is a City ride Car')
        super().__init__(cityride)

class OffRoad(Car):
    def __init__(self, offroading):
        print(offroading, 'is an Off-roading Car')
        super().__init__(offroading)

class SUV(CityRide, OffRoad):
    def __init__(self):
        print('Range Rover is a SUV')
        super().__init__('Range Rover')

c = SUV()
print('')
d = CityRide('Volkswagen Polo')

Output

                    

Range Rover is a SUV
Range Rover is a City ride Car
Range Rover is an Off-roading Car
Range Rover is a Car
Range Rover is a type of Vehicle.

Volkswagen Polo is a City ride Car
Volkswagen Polo is a Car
Volkswagen Polo is a type of Vehicle.

Explanation

Consider the SUV() class instance created; the following are the order of events occurring after it:

  1. The SUV class is called first. SUV() child class is inherited from its parent classes CityRide() and OffRoad().
  2. Using super() in SUV() class, we access the CityRide() and OffRoad() class in that order of definition. First the CityRide() class is called.
  3. Then the OffRoad class is called.
  4. Afterward, by using the super() function, the Car() parent class is called by the OffRoad() child class inheriting its functions and methods.
  5. And finally, the Vehicle class is called.

The flowchart for the above Multiple Inheritance example is as follows –

Python super

Method Resolution Order (MRO)

In the presence of multiple inheritances, Method Resolution Order (MRO) establishes the order in which methods are inherited. MRO specifies where and in what sequence Python will look for a method called with super(). Every class has an MRO, which can be viewed by using the .__mro__ attribute.

Let us look at the above example and find out the MRO for the SUV() class.

Example

Output

                    

(<class '__main__.SUV'>, <class '__main__.CityRide'>, 
<class '__main__.OffRoad'>, <class '__main__.Car'>, 
<class '__main__.Vehicle'>, <class 'object'>)

Explanation

Using MRO, methods in the derived/child class are called first before the base/parent class methods. In the above example, the SUV class is called first, then CityRide class, then in OffRoad class. Then these 2 classes are succeeded by calling the Car class, and Vehicle class afterward. After Vehicle class, If nothing is found, it looks in the object, which is the root of all classes.

In a situation where there are multiple parent classes like (CityRide, OffRoad), methods of the CityRide class will be called first and then OffRoad class because it is specified first in the argument.

FAQs on Python super

Q1. What is super() in Python?

Python super() function is applicable to the concept of Inheritance. To make inheritance more flexible, manageable, and extensible Python provides a built-in function called super(). Using super() to call previously built methods saves you from rebuilding and recoding those methods in your subclass and allowing you to swap out super-classes with minimal code modifications.

The syntax is as follows

Note – There are no arguments accepted by the super() function. Succeeding the Python super() function, you indicate the method you want to inherit from the parent class into that child/sub-class.

Example

                    

super().__init__(parameters)

Q2. Is super() necessary in Python?

The Python super() built-in function is used to return a temporary object of the parent class that also allows us access to its methods in the child class.

The super() function has two primary applications:

  1. To avoid explicitly using the super (parent) class.
  2. To allow working with multiple inheritances.

Python super() is necessary because –

  • It is not necessary to know or specify the parent class name in order to access its functions.
  • Python super() function is applicable to both single and multiple inheritances.
  • Because there is no need to rewrite the complete function again, this implements flexibility, modularity, and code reusability.
  • Because Python, unlike other languages, is a dynamic language, super functions are called dynamically.

Q3. What does super() do in Django?

Python super() function is no different for the Django framework. In Django, we implement the super() function just like we implement it in Python.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

avatar
  Subscribe  
Notify of

Customize your course in 30 seconds

Which class are you in?
No thanks.