Introduction to Python Super With Examples

We all have must use Inheritance at some point in time or at least have heard how useful it is any object-oriented programming language. It allows one class (derived class) to obtain all the parent (base) class properties. The derived class can access the base class variables, methods. And to access the methods of the base inside the derived class, we have python super method.

This Python super() method is a built-in method that creates a proxy object (temporary object) inside the derived class. To understand it better, we can think of it as a way to access the methods of the superclass(base) from the derived class. If you are thinking about what we will do by accessing those methods, trust me, it all depends on our imagination how well we use it. And this question of you will surely be answered by the end of this article.

Python Super in Different Levels of Inheritance

Following are the different levels of inheritance using super –

1. Python super() in Single Inheritance

In single Inheritance, there is only one base class and one derived class. And in Python, each class has a constructor named __init__. To know more about the __init__, refer to this article – https://www.pythonpool.com/init-python/

class Vehicle:
  def __init__(self,name,gear,model):
    self.name=name
    self.gear=gear
    self.model=model
class Car(Vehicle):
  def __init__(self,name,gear,model,types):
  # calling the __init__ method of the superclass
     super().__init__(name,gear,model)
     self.types=types
car1=Car("car",'5','2010',"hatchback")
car2=Car("car",'5','2003',"Sedan")
print("The number of gear in car1",car1.gear)
print("Car1 model year",car1.model)
print("Type of car1",car1.types)
print("The number of gear in car2",car2.gear)
print("Car2 model year",car2.model)
print("Type of car2",car2.types)
Output-
The number of gear in car1 5
Car1 model year 2010
Type of car1 hatchback
The number of gear in car2 5
Car2 model year 2003
Type of car2 Sedan

We can also do-

class Vehicle:
  def __init__(self,name,gear,model):
    self.name=name
    self.gear=gear
    self.model=model
class Car(Vehicle):
   def __init__(self,name,gear,model,types):
   # calling the__init__ method of the superclass
       Vehicle.__init__(self,name,gear,model)
       self.types=types
car1=Car("car",'5','2010',"hatchback")
car2=Car("car",'5','2003',"Sedan")
print("The number of gear in car1",car1.gear)
print("Car1 model year",car1.model)
print("Type of car1",car1.types)
print("The number of gear in car2",car2.gear)
print("Car2 model year",car2.model)
print("Type of car2",car2.types)`
Output-
The number of gear in car1 5
Car1 model year 2010
Type of car1 hatchback
The number of gear in car2 5
Car2 model year 2003
Type of car2 Sedan


But suppose we want to change the Parent class, think, to a class named four-wheelers. And if we have used the second approach, we would have to change it everywhere we have used the Vehicle.__init__(). So, using super is the best option available.

Note – super() has two parameters. If we do not value these parameters, the default values here will be super(Car, self). Here the first argument is the subclass, and second is the instance of the subclass.

2. Python in Multilevel Inheritance

There is a base class A, a derived class B, which is the base class to C and a derived class C in multilevel Inheritance.
Here, we can create a program that will calculate the age of the father and Grandfather(Note that here we have assumed that the age of a father is 25 more than child and age of grandfather is 25 more than the father.) This is quite an unrealistic example, but I think it will help you understood the working of super() better.

class GrandFather:
  def __init__(self): 
    print('GrandFather born')
  def calculate_age(self, age):
    print('Age of GrandFather', age)

class Father(GrandFather):
  def __init__(self):
    super().__init__()
    print('Father born')
  def calculate_age(self, age):
    super().calculate_age(age + 25)
    print('Age of Father', age)

class Child(Father):
  def __init__(self):
    super().__init__()
    print('Child born')
  def calculate_age(self, age):
    super().calculate_age(age + 25)
    print('Age of Child:', age)

c = Child()
c.calculate_age(18)
Output-
GrandFather born
Father born
Child born
Age of GrandFather 68
Age of Father 43
Age of Child: 18

3. Python Super() in Multiple Inheritance

In multiple Inheritance, we have one derived class and more than one base class. For example- A child derives properties from mother and father. Now let us see how super() can help us in multiple Inheritance.

class Animal: 
  def __init__(self, name):
    print(name, 'is an animal.')

class CannotFly(Animal):
  def __init__(self,name):
    print(name, "cannot fly.")
    super().__init__(name)

#Cat derives the property of animal and those type of animals #that cannot fly
class Cat(CannotFly,Animal):
  def __init__(self):
    print('I am a cat.');
    super().__init__('Cat')
cat = Cat()
Output
I am a cat.
Cat cannot fly.
Cat is an animal.
Method Resolution Order

Method Resolution Order

Method Resolution Order or MRO helps Python find out the order in which the execution of inherited methods will occur. It is super handy when we are using super() because the MRO tells Python exactly where to look for a method we call with super() and in what order. We can use the __mro__ attribute for this purpose.

Let’s look at the same example from the previous section.

class Animal: 
  def __init__(self, name):
    print(name, 'is an animal.')

class CannotFly(Animal):
  def __init__(self,name):
    print(name, "cannot fly.")
    super().__init__(name)

#Cat derives the property of animal and those type of animals #that cannot fly
class Cat(CannotFly,Animal):
  def __init__(self):
    print('I am a cat.');
    super().__init__('Cat')
cat = Cat()
print(Cat.mro)
Output-
(main.Cat, main.CannotFly, main.Animal, object)

It clearly shows that the first method inside Cat class will be called, then the method inside the CannotFly class will be called, and finally, the method inside Animal class will be called.

Must Read

Conclusion

From all that we have discussed until now, we must have understood how important python super() is to make a developer-friendly and user-friendly code. It makes it so easy to access the methods inside the superclass implicitly from the subclass.

Try to run the programs on your side and let me know if you have any queries.

Happy Coding!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments