Table of contents
1.
Introduction
2.
What is super() in Python?
3.
Syntax of super() in Python
4.
super() function in Python Example
4.1.
Python
5.
What is the super () method used for?
5.1.
Examples of Using super() in Python
5.1.1.
1. Basic Example of super() in Single Inheritance
5.2.
Python
5.2.1.
2. Using super() in Multiple Inheritance
5.3.
Python
6.
Benefits of Super Function
7.
How does Inheritance work without  Python super?
7.1.
Python
8.
Understanding Python super() with __init__() methods
8.1.
Super with Single Inheritance
8.2.
Python
8.3.
Super with Multiple Inheritance
8.4.
Python
8.5.
Method Resolution Order
8.6.
Python
9.
Understanding Python super() with __init__() Methods
9.1.
Example: Using super() in Single Inheritance
9.2.
Python
10.
Frequently Asked Questions
10.1.
What does super do in Python classes?
10.2.
What is super () __ Init__?
10.3.
Why do I need super () Python?
10.4.
What is the super key in Python?
11.
Conclusion
Last Updated: Nov 9, 2024
Easy

Python Super()

Author Rishabh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Python, inheritance allows a class to inherit methods and attributes from a parent class, facilitating code reuse and organization. The super() function is a powerful tool that simplifies the calling of methods from a superclass, especially in complex inheritance hierarchies. By using super(), you can invoke the parent class’s methods without explicitly naming it, ensuring that your code is more maintainable and scalable. In this blog, we’ll explore how the super() function works.

python super

What is super() in Python?

The Python super function allows us to call a method from a parent class in a subclass. This is used whenever we want to override a method in the parent class while using some of its functionality. It makes the code more readable and more efficient as we do not need to repeat the code from the parent class. This makes inheritance more manageable and extensible.

Syntax of super() in Python

Here is the syntax of the function super() in Python, which can call a method from a parent class in a subclass:

super()


In the syntax of super(), no argument is passed, and it returns a proxy object representing the parent's class.

super() function in Python Example

In this example, we will create a class ‘Student’ with __init__ method that will initialize the properties such as id, name, and age. Then we will create the class ‘Students’ where the ‘Student’ class is inherited with one more property called email. So now, the object of the ‘Students’ class will be created with the values passed to the constructor, and lastly, all the values of the properties will be printed.

  • Python

Python

class Student():
def __init__(self, id, name, age):
self.id = id
self.name = name
self.age = age

# Class Students inherits Student
class Students(Student):
def __init__(self, id, name, age, email):
super().__init__(id, name, age)
self.email = email

# Creating object of class Students
stud1 = Students(63, "Ninja 1", 21 , "ninja_coder@gmil.com")
# Printing the value of every property of class Students and Student
print('Student ID:', stud1.id)
print('Student Name:', stud1.name)
print('Student Address:', stud1.age)
print('Student Email:', stud1.email)
You can also try this code with Online Python Compiler
Run Code

Output

output

What is the super () method used for?

The super() method in Python is used for the typical practice in object-oriented programming that can call the methods of the superclass and the features such as inheritance and method overriding can be enabled.

Examples of Using super() in Python

The super() function is primarily used in object-oriented programming to call methods from a parent class. It’s useful in situations where you want to extend or modify inherited behavior without directly referencing the parent class by name. Below are some examples demonstrating how to use super() in Python.

1. Basic Example of super() in Single Inheritance

In a simple inheritance structure, super() can be used to call a method from the parent class.

  • Python

Python

class Animal:
def speak(self):
print("Animal makes a sound")

class Dog(Animal):
def speak(self):
super().speak() # Calls the method from the parent class
print("Dog barks")

dog = Dog()
dog.speak()
You can also try this code with Online Python Compiler
Run Code

 

Output:

Animal makes a sound
Dog barks

Explanation:
In this example, the Dog class inherits from the Animal class. Inside the speak() method of the Dog class, we use super().speak() to call the speak() method of the Animal class before printing the Dog-specific behavior.

2. Using super() in Multiple Inheritance

When working with multiple inheritance, super() ensures that the method resolution order (MRO) is respected and the correct methods are called from parent classes.

  • Python

Python

class Animal:
def speak(self):
print("Animal makes a sound")

class Mammal(Animal):
def speak(self):
super().speak() # Calls Animal's speak()
print("Mammal makes a sound")

class Dog(Mammal):
def speak(self):
super().speak() # Calls Mammal's speak()
print("Dog barks")

dog = Dog()
dog.speak()
You can also try this code with Online Python Compiler
Run Code

 

Output:

Animal makes a sound
Mammal makes a sound
Dog barks

Benefits of Super Function

  • By using python super we do not need to write the whole function again as we can reuse the same code further.
     
  • Using python Super makes the code more explicit and has a better readability.
     
  • We do not need to write the parent class name to access its methods. Python Super can also be used both in single and multiple inheritance.

How does Inheritance work without  Python super?

Let’s look how the inheritance is working without super. 

Here, we define two classes: “Person” and “people”, with “people” inheriting from “Person”. Let's try to access name_ and name properties of the object people_details.

  • Python

Python

class Person:

# Constructor
def __init__(self, name, age):
self.name = name
self.age = age

# To check the details about a person
def Display(self):
print(self.name, self.age)

class people(Person):

def __init__(self, name, age):
self.name_ = name

def Print(self):
print("people class called")

people_details = people("Rahul", 18)

# Calling parent class function
people_details.name_, people_details.name
You can also try this code with Online Python Compiler
Run Code

Output 

Here, code gives error while accessing the name_ and name properties of the object because these properties are not defined in any of the classes. 

Let's look at how we use super functions in python for the working of inheritance. 

Understanding Python super() with __init__() methods

  • super() is used to call _init_() method of the parent class which allows it to inherit the parent’s class behaviour to the child’s class behaviour.
  • We can directly call _init_() from parent’s class by super._init_().
  • We do not need to pass a child instance as an argument while calling super._init_().

Super with Single Inheritance

Single inheritance refers to when a child class inherits from a single-parent class, thereby using the parent class's methods and attributes. 

Let's look at an example to use python super function with single inheritance. Here, the child class inherits from the Parent class and overrides its my_name method.

  • Python

Python

# Define a class called "Parent"
class Parent:
# Initialize the object with a "name" attribute

def __init__(self, name):
self.name = name

# Define a method called "my_name"

def my_name(self):
print(f"My name is {self.name}.")

# Define a class called "Child"
# That inherits from "Parent"

class Child(Parent):
# Initialize the object with "name"
# And "age" attributes
def __init__(self, name, age):
super().__init__(name)
self.age = age

def my_name(self):
super().my_name()
print(f"I am {self.age} years old.")

# New instance of the "Child" class
child = Child("Rahul", 18)

# Call the "my_name" method
child.my_name()
You can also try this code with Online Python Compiler
Run Code


Output 

output

Super with Multiple Inheritance

Multiple inheritance refers to when a child class inherits from a multiple-parent class, thereby using the parent class's methods and attributes. 

Let's look at an example to use python super function with multiple inheritance. Here, ChildClass inherits from BaseClass1 and BaseClass2 using multiple inheritance.

  • Python

Python

# Define a class called "BaseClass1"
class BaseClass1:
def __init__(self):
print("Parent Class 1")

# Define a class called "BaseClass2"
class BaseClass2:
def __init__(self):
print("Parent Class 2")

# Define a class called "ChildClass"
# That inherits from both "BaseClass1" and "BaseClass2"
class ChildClass(BaseClass1, BaseClass2):
def __init__(self):
super().__init__()
print("Child Class")

# Create a new instance of the "ChildClass"
child = ChildClass()
You can also try this code with Online Python Compiler
Run Code


Output

output

Method Resolution Order

The order in which the interpreter searches for methods to run in a class hierarchy is known as the Method Resolution Order (MRO) in Python. 

Python initially searches the object's class for the method when a method is invoked on an object. The search continues up the hierarchy until it finds the method or reaches the top of the hierarchy if it is not found there.

Let's see with an example. Here, we have defined a class hierarchy where a class child inherits from classes parent2 and parent3, which in turn inherit from a class parent, and uses super() to call the next method in the MRO. 

  • Python

Python

# Define a class called "parent"
class parent:
def f(self):
print("Parent 1")

# Define a class called "parent2"
# That inherits from "parent"
class parent2(parent):
# Call the parent's "f" method using
# The "super()" function and print a message
def f(self):
super().f()
print("Parent 2")

# Define a class called "parent3"
# That inherits from "parent"
class parent3(parent):
def f(self):
print("Parent 3")

# Define a class called "child" that
# Inherits from "parent2" and "parent3"
class child(parent2, parent3):
# Call the parent's "f" method using
# The "super()" function and print a message
def f(self):
super().f()
print("Child")

# Create an instance of the "child"
d = child()
d.f()
You can also try this code with Online Python Compiler
Run Code


Output

output

Understanding Python super() with __init__() Methods

In Python, the super() function is commonly used in the __init__() method to call the constructor of the parent class. This is particularly useful when you are working with inheritance, as it ensures that the parent class’s initialization is properly executed, and any attributes or behavior it defines are set up correctly.

The __init__() method is the constructor in Python, automatically called when an instance of a class is created. When you override this method in a subclass, you might want to ensure that the parent class's constructor is also executed to properly initialize inherited attributes.

The super() function allows you to call the parent class’s __init__() method without explicitly naming the parent class, making the code more flexible, especially when dealing with multiple inheritance.

Example: Using super() in Single Inheritance

In this example, we have a Person class and a Student class. The Student class inherits from Person, and we use super() to call the __init__() method of the Person class.

  • Python

Python

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print(f"Person: {self.name}, {self.age} years old")

class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age) # Call the parent class's __init__()
self.student_id = student_id
print(f"Student ID: {self.student_id}")

# Create an instance of Student
student = Student("Rahul", 20, "S12345")
You can also try this code with Online Python Compiler
Run Code

 

Output:

Person: Rahul, 20 years old
Student ID: S12345

Explanation:
In the Student class, we use super().__init__(name, age) to call the __init__() method of the Person class, ensuring that the name and age attributes are initialized correctly. The Student class then initializes its own student_id attribute. This approach allows the Student class to reuse the initialization code of the Person class.

Frequently Asked Questions

What does super do in Python classes?

super() in Python provides a mechanism to invoke methods from a parent class, facilitating cooperative multiple inheritance by maintaining a consistent method resolution order.

What is super () __ Init__?

super().__init__ is used to call the constructor of the parent class in Python. It's often employed in a subclass constructor to initialize the inherited attributes.

Why do I need super () Python?

super() ensures proper method delegation in class hierarchies, promoting code reusability and maintaining a clear method resolution order, especially in scenarios involving multiple inheritance.

What is the super key in Python?

There isn't a "super key" in Python. super() is a built-in function used for calling methods from a superclass, crucial for maintaining consistent inheritance hierarchies in object-oriented programming.

Conclusion

In this article, we discussed the Python Super(). The super() function is a powerful and versatile tool in Python, enabling seamless interaction with parent class methods, especially in the context of inheritance. Whether you're working with simple single inheritance or complex multiple inheritance, super() helps ensure that parent class methods are properly called, allowing for cleaner, more maintainable code.

To learn more, check out our articles:

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Code360!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Live masterclass