Skip to content
Related Articles
Open in App
Not now

Related Articles

Python super()

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 12 Sep, 2022
Improve Article
Save Article

How Inheritance is working without super

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'

In above code Emp class is inherits the Person class

  • Both class has the __init__ constructor
  • trying to call name & name_ from other class 
  • But we will encounter the above error

With super implementation in inherent we can solve the problem. example can found below

The Python super() function returns objects represented in the parent’s class and is very useful in  multiple and multilevel inheritances to find which class the child class is extending first.

Syntax of super() in Python

Syntax: super()

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

Example of super() function in Python

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

Solving the first problem using super

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

The benefits of using a super() function are:

  • 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.
  • Super function in Python is called dynamically because Python is a dynamic language, unlike other languages.

Super function in 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 function in multiple inheritances

Let’s take another example of a super function, Suppose a class canfly and canswim 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

MRO in Multiple Inheritance

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'>]

Multi-Level inheritance

Let’s take another example of a super function, suppose a class canSwim is inherited by canFly, canFly from 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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!