Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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?
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.
Frequently Asked Questions
9.1.
What does super do in Python classes?
9.2.
What is super () __ Init__?
9.3.
Why do I need super () Python?
9.4.
What is the super key in Python?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Python Super()

Author Rishabh
0 upvote

Introduction

In Python programming, the super() function stands as a cornerstone for effective and maintainable object-oriented design. As developers navigate the complexities of inheritance and method resolution, super() emerges as a guiding force, offering a unique approach to handle calls to parent class methods.

python super

We will look closely at how Python Super works.

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)

Output

super() function in Python Example - 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.

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

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()


Output 

Output for Super with Single Inheritance

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()


Output

Output for Super with Multiple Inheritance

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()


Output

Output for Method Resolution Order

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 Function. The Python super() function is like a guiding star in the world of coding with Python. It helps us organize our code better and reuse it wisely.

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 Coding Ninjas Studio!

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!

Happy Learning!

Live masterclass