Open In App

Python super()

Improve
Improve
Like Article
Like
Save
Share
Report

In Python, the super() function is used to refer to the parent class or superclass. It allows you to call methods defined in the superclass from the subclass, enabling you to extend and customize the functionality inherited from the parent class.

Syntax of super() in Python

Syntax: super()

Return : Return a proxy object which represents the parent’s class.

super() function in Python Example

In the given example, The Emp class has an __init__ method that initializes the id, and name and Adds attributes. The Freelance class inherits from the Emp class and adds an additional attribute called Emails. It calls the parent class’s __init__ method super() to initialize the inherited attribute.

Python3




class Emp():
    def __init__(self, id, name, Add):
        self.id = id
        self.name = name
        self.Add = Add
 
# Class freelancer inherits EMP
class Freelance(Emp):
    def __init__(self, id, name, Add, Emails):
        super().__init__(id, name, Add)
        self.Emails = Emails
 
Emp_1 = Freelance(103, "Suraj kr gupta", "Noida" , "KKK@gmails")
print('The ID is:', Emp_1.id)
print('The Name is:', Emp_1.name)
print('The Address is:', Emp_1.Add)
print('The Emails is:', Emp_1.Emails)


Output :

The ID is: 103
The Name is: Suraj kr gupta
The Address is: Noida
The Emails is: KKK@gmails

What is the super () method used for?

A method from a parent class can be called in Python using the super() function. It’s typical practice in object-oriented programming to call the methods of the superclass and enable method overriding and inheritance. Even if the current class has replaced those methods with its own implementation, calling super() allows you to access and use the parent class’s methods. By doing this, you may enhance and modify the parent class’s behavior while still gaining from it.

Benefits of Super Function

  • Need not remember or specify the parent class name to access its methods. This function can be used both in single and multiple inheritances.
  • This implements modularity (isolating changes) and code reusability as there is no need to rewrite the entire function.
  • The super function in Python is called dynamically because Python is a dynamic language, unlike other languages.

How does Inheritance work without  Python super?

In the given example, there is an issue with the Emp class’s __init__ method. The Emp class is inherited from the Person class, but in its __init__ method, it is not calling the parent class’s __init__ method to initialize the name and id attributes.

Python3




# code
class Person:
 
    # Constructor
    def __init__(self, name, id):
        self.name = name
        self.id = id
 
    # To check if this person is an employee
    def Display(self):
        print(self.name, self.id)
     
 
class Emp(Person):
     
    def __init__(self, name, id):
        self.name_ = name
 
    def Print(self):
        print("Emp class called")
 
Emp_details = Emp("Mayank", 103)
 
# calling parent class function
Emp_details.name_, Emp_details.name


Output :

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-46ffda859ba6> in <module>
     24 
     25 # calling parent class function
---> 26 Emp_details.name_, Emp_details.name

AttributeError: 'Emp' object has no attribute 'name'

Fixing the above problem with Super in Python

In the provided code, the Emp class is correctly inheriting from the Person class, and the Emp class’s __init__ method is now properly calling the parent class’s __init__ method using super() in Python.

Python3




# code
# A Python program to demonstrate inheritance
 
class Person:
 
    # Constructor
    def __init__(self, name, id):
        self.name = name
        self.id = id
 
    # To check if this person is an employee
    def Display(self):
        print(self.name, self.id)
     
 
class Emp(Person):
     
    def __init__(self, name, id):
        self.name_ = name
        super().__init__(name, id)
 
    def Print(self):
        print("Emp class called")
 
Emp_details = Emp("Mayank", 103)
 
# calling parent class function
print(Emp_details.name_, Emp_details.name)


Output :

Mayank Mayank

Understanding Python super() with __init__() methods

Python has a reserved method called “__init__.” In Object-Oriented Programming, it is referred to as a constructor. When this method is called it allows the class to initialize the attributes of the class. In an inherited subclass, a parent class can be referred to with the use of the super() function. The super function returns a temporary object of the superclass that allows access to all of its methods to its child class.

Note: For more information, refer to Inheritance in Python.

Super function with Single Inheritance 

Let’s take the example of animals. Dogs, cats, and cows are part of animals. They also share common characteristics like –  

  • They are mammals.
  • They have a tail and four legs.
  • They are domestic animals.

So, the classes dogs, cats, and horses are a subclass of animal class. This is an example of single inheritance because many subclasses is inherited from a single-parent class.

Python3




# Python program to demonstrate
# super function
 
class Animals:
    # Initializing constructor
    def __init__(self):
        self.legs = 4
        self.domestic = True
        self.tail = True
        self.mammals = True
 
    def isMammal(self):
        if self.mammals:
            print("It is a mammal.")
 
    def isDomestic(self):
        if self.domestic:
            print("It is a domestic animal.")
 
class Dogs(Animals):
    def __init__(self):
        super().__init__()
 
    def isMammal(self):
        super().isMammal()
 
class Horses(Animals):
    def __init__(self):
        super().__init__()
 
    def hasTailandLegs(self):
        if self.tail and self.legs == 4:
            print("Has legs and tail")
 
# Driver code
Tom = Dogs()
Tom.isMammal()
Bruno = Horses()
Bruno.hasTailandLegs()


Output :

It is a mammal.
Has legs and tail

Super with Multiple Inheritances

Let’s take another example of a super function, Suppose a class can fly and can swim inherit from a mammal class and these classes are inherited by the animal class. So the animal class inherits from the multiple base classes. Let’s see the use of Python super with arguments in this case.

Python3




class Mammal():
 
    def __init__(self, name):
        print(name, "Is a mammal")
 
class canFly(Mammal):
 
    def __init__(self, canFly_name):
        print(canFly_name, "cannot fly")
 
        # Calling Parent class
        # Constructor
        super().__init__(canFly_name)
 
class canSwim(Mammal):
 
    def __init__(self, canSwim_name):
 
        print(canSwim_name, "cannot swim")
 
        super().__init__(canSwim_name)
 
class Animal(canFly, canSwim):
 
    def __init__(self, name):
        super().__init__(name)
 
# Driver Code
Carol = Animal("Dog")


Output :

The class Animal inherits from two-parent classes – canFly and canSwim. So, the subclass instance Carol can access both of the parent class constructors. 

Dog cannot fly
Dog cannot swim
Dog Is a mammal

Super with Multi-Level Inheritance

Let’s take another example of a super function, suppose a class can swim is inherited by canFly, canFly from the mammal class. So the mammal class inherits from the Multi-Level inheritance. Let’s see the use of Python super with arguments in this case.

Python3




class Mammal():
 
    def __init__(self, name):
        print(name, "Is a mammal")
 
 
class canFly(Mammal):
 
    def __init__(self, canFly_name):
        print(canFly_name, "cannot fly")
 
        # Calling Parent class
        # Constructor
        super().__init__(canFly_name)
 
 
class canSwim(canFly):
 
    def __init__(self, canSwim_name):
 
        print(canSwim_name, "cannot swim")
 
        super().__init__(canSwim_name)
 
 
class Animal(canSwim):
 
    def __init__(self, name):
 
        # Calling the constructor
        # of both the parent
        # class in the order of
        # their inheritance
        super().__init__(name)
 
 
# Driver Code
Carol = Animal("Dog")


Output :

Dog cannot swim
Dog cannot fly
Dog Is a mammal

Python Multiple Inheritance and MRO

In the given example, class C inherits from classes A and B, and it overrides the age() method. However, in the age() method of class C, the super(C, self).age() line invokes the age() method from the next class in the MRO. In this case, it will invoke the age() method from class A since it appears before class B in the MRO.

Python3




class A:
    def age(self):
        print("Age is 21")
class B:
    def age(self):
        print("Age is 23")
class C(A, B):
    def age(self):
        super(C, self).age()
     
c = C()
print(C.__mro__)
print(C.mro())


Output :

(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]


Last Updated : 26 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads