The built-in function super() is a mechanism to refer parent class without naming it in Python. Super() creates a temporary object that helps in accessing the parent class’s methods and attributes. It’s like super() delegates accessing functionality it to an object during run time.
Python super() function is used for accessing the methods and properties of the base class or superclass. A super function returns a proxy object.
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
class Student(Person):
def __init__(self,name,age,grade):
super().__init__(name,age)
self.grade = grade
def printGrade(self):
print('Student name is {} age is{} and Grade is{}'.format(self.name,self.age,self.grade))
stud1 = Student('Gokul',24,'A')
stud1.printGrade()
Output:
Student name is Gokul age is 24 and Grade is A
From the above program, we can see that we have used the instances of the parent class in the child class using the super keyword, like this we can also call methods that are defined inside the parent class into the child class.
super() with Single Inheritance
Inheritance in object-oriented programming allows you to create a class hierarchy where one child class inherits all methods from another parent class. This simplifies the development of large software projects and avoids redundant code.
class Organism:
def __init__(self):
print('I live')
class Human(Organism):
def __init__(self):
print('I am human')
super().__init__()
alice = Human()
Output:
I am human
I live
Here you call the base class Organism using the following code:
super().__init__()
A semantically equivalent code call would be:
Organism.__init__(self)
super() with Multiple Inheritance
One of Python’s unique features compared to other programming languages is that it allows multiple inheritance.
Multiple inheritance means that a class can inherit from multiple parents. For example, a class Human
can inherit from two parent classes: Organism
and Thinker
. Say, you define a method live()
in Organism and think()
in Thinker. If a Human object inherits from both classes, it can call live()
and think()
at the same time! You use the super()
method to call those functions:
class Organism:
def live(self):
print('I live')
class Thinker:
def think(self):
print('I think')
class Human(Organism, Thinker):
def __init__(self):
print('I am human')
super().live()
super().think()
alice = Human()
Output:
I am human
I live
I think
Summary
Python’s built-in super()
method returns a temporary object of the superclass to help you access its methods. Its purpose is to avoid using the base class name explicitly. It also enables your class to inherit from multiple base classes.