Super() Function in Python

Super() Function in Python

5 mins read234 Views Comment
Updated on Mar 30, 2023 12:49 IST

The super() function is used to give access to methods and properties of a parent or sibling class.This articles is explaining super() function in detail.It covers this topic with various examples in python and have also covered Method Resolution Order.

2023_03_MicrosoftTeams-image-6-1.jpg

In Python, the super function is utilized to obtain access to immediate parent class methods. In this article, we will discuss the super() function and understand its use with the help of examples. We will be covering the following sections:

Introduction super() Function in Python

In Python, super() is a built-in function that allows access to methods and properties of a parent or superclass from a child or subclass. This is useful when working with inheritance in object-oriented programming. It enables a subclass to inherit behaviour and attributes from its parent class while also providing the flexibility to override or extend that behaviour in the subclass. 

By using super(), you can call a method from the parent class without explicitly naming the parent class, which can make your code more flexible and easier to maintain.

With Statement in Python
Understanding Swapcase in Python
What is Capitalize in Python?

Explore Online Python Courses

Explore programming courses

Syntax of super()

The syntax of the super() function in Python is given as follows:


 
class ChildClass(ParentClass):
def method(self, arg):
super([ChildClass], [self]).method(arg)
Copy code

Parameters of super()

This function takes two optional parameters:

·     ChildClass: This is the name of the subclass.

·     ClassObject: This is an object of the subclass.

Return Value of super()

Return Type: <class ‘super’>

This function returns a temporary proxy object for the immediate parent class, and this proxy can be utilized to invoke methods of the parent class.

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

Examples of Using the super() Function in Python

Example 1: Overriding a Method in a Subclass


 
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_details(self):
return f"Name: {self.name}, Age: {self.age}"
class Employee(Person):
def __init__(self, name, age, id):
super().__init__(name, age)
self.id = id
def get_details(self):
return f"Name: {self.name}, Age: {self.age}, ID: {self.id}"
emp = Employee("John Doe", 30, 1234)
print(emp.get_details())
Copy code

Output:

Name: John Doe, Age: 30, ID: 1234

In this example, Person is the parent class, and Employee is the child class inherited from Person. The Employee class has its get_details() method that overrides the method in the parent class. However, the Employee class must also call the parent class’s __to init__() method to initialize the name and age attributes. This is where super() comes in handy by calling super().__init__(name, age), we can initialize the name and age attributes in the parent class and then add the id attribute in the child class.

Difference Between Module and Package in Python
Calculator Program in Python: A Step-By-Step Guide
Difference Between Jupyter Notebook and Python IDLE

Example 2: Multiple Inheritance


 
class A:
def some_method(self):
print("This is method A")
class B:
def some_method(self):
print("This is method B")
class C(A, B):
def some_method(self):
super().some_method()
c = C()
c.some_method()
Copy code

Output:

This is method A 

In this example, C is a child class inherited from A and B. Both A and B have a method named some_method(), but C overrides this method to call super().some_method(). Since A comes before B in the inheritance list, super().some_method() will call the some_method() method of A

Example 3: Dynamically Choosing the Parent Class


 
class Shape:
def __init__(self, color):
self.color = color
class Square(Shape):
def __init__(self, color, side_length):
super(type(self), self).__init__(color)
self.side_length = side_length
sq = Square("red", 5)
print(sq.color)
Copy code

Output:

red 

In this example, the Square class inherits from Shape. However, instead of hardcoding the parent class name in the super() call, we use type(self) to choose the parent class dynamically. This allows us to change the inheritance hierarchy without changing the code. 

Example 4: Using super() with Class and Static Methods


 
class A:
@classmethod
def some_classmethod(cls):
print("This is classmethod A")
@staticmethod
def some_staticmethod():
print("This is staticmethod A")
class B(A):
@classmethod
def some_classmethod(cls):
super().some_classmethod()
print("This is classmethod B")
@staticmethod
def some_staticmethod():
super().some_staticmethod()
print("This is staticmethod B")
B.some_classmethod()
# Output: This is classmethod A, This is classmethod B
B.some_staticmethod()
# Output: This is staticmethod A, This is staticmethod B
Copy code

# Output: This is staticmethod A, This is staticmethod B 

In this example, B is a child class that inherits from A, and both classes have a class method and a static method. In B, we override both methods and call super() to call the corresponding methods in A, before adding the behavior of B

Method Resolution Order 

What is Method Resolution Order? Explain with the help of an example in Python

Method Resolution Order (MRO) is the order in which Python looks for methods to execute in a class hierarchy. When a method is called on an instance of a class, Python looks for the method in the instance’s class first, then in the class’s parent class, and so on, until it finds the method or reaches the top of the hierarchy. The order in which Python searches for methods is determined by the MRO of the classes in the hierarchy.

In Python, the MRO is determined using the C3 linearization algorithm, which considers the order in which classes are inherited, and ensures that each method in the inheritance graph is called exactly once. The MRO is stored in the __mro__ attribute of a class.

Here’s an example to illustrate MRO in Python: 


 
class Parent:
def __init__(self):
print("This is the parent class")
class Parent1:
def __init__(self):
print("This is the parent1 class")
class Child(Parent1, Parent):
def __init__(self):
##Calling constructor of the Parnet 1 class
super().__init__()
print(Child.mro())
Copy code

Output:

[<class ‘__main__.Child’>, <class ‘__main__.Parent1’>, <class ‘__main__.Parent’>, <class ‘object’>] 

The output clarifies that the Child class extends the Parent1 class first and then extends the Parent class. In Python, the object class is the top-level class that is the superclass for all other classes. Therefore, by default, the Child class also extends the object class.

Now, how do we access methods of the Parent class using the super() function? 


 
class Parent:
def __init__(self):
print("This is the parent class")
class Parent1:
def __init__(self):
print("This is the parent1 class")
class Child(Parent1, Parent):
def __init__(self):
##Calling constructor of the Parent 1 class
super(Parent1, self).__init__()
ob = Child()
Copy code

Output:

This is the parent class 

As you can see, the parent class’s constructor is accessed here using the super() function in the Child class.

Endnotes

Hope this article was helpful for you in understanding how and why the super() method is used in Python. You can explore related articles here if you wish to learn more about Python and practice Python programming.

Contributed by -Prerna Singh

FAQs

Why use super() instead of calling the parent class directly?

Using super() allows for more flexibility in class hierarchies, as it automatically handles changes to the hierarchy and makes it easier to write maintainable and reusable code.

How does super() work?

super() works by returning a proxy object that delegates method calls to a parent or sibling class in the method resolution order (MRO) of the current class.

What is the MRO?

The method resolution order (MRO) is the order in which Python looks for methods to execute in a class hierarchy. The MRO is determined using the C3 linearization algorithm, which takes into account the order in which classes are inherited and ensures that each method in the inheritance graph is called exactly once.

Can super() be used with multiple inheritances?

Yes, super() can be used with multiple inheritances. When using super() in a subclass that has multiple superclasses, it calls the next method in the MRO of the first argument passed to super().

How do I use super() to call a method of a parent class?

To use super() to call a method of a parent class, you first need to pass the subclass and an instance of the subclass to super(), along with the method name as a string. For example: super(Subclass, self).parent_method_name()

Is super() specific to Python?

No, the concept of a superclass and the ability to call methods of a superclass using a special syntax is present in many object-oriented programming languages. However, the specific syntax and behavior of super() may differ between languages.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio