Python super() Function
What is super()
?
The super()
function in Python is used to call methods from a parent class inside a child class.
It's mostly used in inheritance when:
- You want to call a parent class’s constructor (
__init__()
). - You want to reuse code from the parent class.
Syntax
super().method_name(arguments)
Example 1: Using super()
to Call Parent Constructor
class Person:
def __init__(self, name):
self.name = name
print("Person constructor called")
class Student(Person):
def __init__(self, name, roll):
super().__init__(name)
self.roll = roll
print("Student constructor called")
s = Student("Simran", 101)
print(s.name)
print(s.roll)
Output:
Person constructor called
Student constructor called
Simran
101
Explanation:
super().__init__(name)
calls the__init__
ofPerson
.- This initializes
name
in the base class. - Then
roll
is added in the child class.
Example 2: Call Parent Method from Child
class A:
def show(self):
print("Class A")
class B(A):
def show(self):
super().show()
print("Class B")
b = B()
b.show()
Output:
Class A
Class B
Explanation:
super().show()
inside classB
callsA
’sshow()
method before continuing.
Example 3: Multiple Inheritance with super()
class Base:
def show(self):
print("Base")
class Left(Base):
def show(self):
super().show()
print("Left")
class Right(Base):
def show(self):
super().show()
print("Right")
class Derived(Left, Right):
def show(self):
super().show()
print("Derived")
d = Derived()
d.show()
Output:
Base
Right
Left
Derived
Explanation:
- Python uses Method Resolution Order (MRO) to decide which
super()
call to resolve. - You can view it with
print(Derived.__mro__)
.
When to Use super()
Use Case | Benefit |
---|---|
Calling parent class constructor | Avoid duplicate code |
Method overriding | Extend or enhance parent behavior |
Multiple inheritance | Follow MRO chain cleanly |