Python super()
Function
The super() function in Python is used to call methods from a parent or superclass. It's commonly used in inheritance to avoid repeating code and make child classes more manageable.
Syntax
super().method_name(arguments)
Parameters:
- Returns a proxy object that delegates method calls to a parent class.
- Commonly used inside methods of child classes.
Returns:
- A temporary object of the superclass that allows you to call its methods.
Why Use super()
?
- To reuse code from a parent class.
- To avoid hardcoding parent class names (supports clean inheritance).
- To maintain better support for multiple inheritance.
Example 1: Basic Inheritance
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
def greet(self):
super().greet()
print("Hello from Child")
c = Child()
c.greet()
Hello from Parent
Hello from Child
Example 2: Using super()
in __init__()
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
d = Dog("Buddy", "Labrador")
print(d.name)
print(d.breed)
Buddy
Labrador
Multiple Inheritance Example
class A:
def process(self):
print("A.process()")
class B(A):
def process(self):
print("B.process()")
super().process()
class C(B):
def process(self):
print("C.process()")
super().process()
c = C()
c.process()
C.process()
B.process()
A.process()
Common Mistakes
- Calling
super()
outside a class method will raise an error. - Do not forget to call
super().__init__()
in child constructors to properly initialize inherited attributes.
Interview Tip
super()
is frequently tested in OOP interviews to check your understanding of inheritance and code reuse. You may be asked to rewrite code using super()
to make it cleaner.
Summary
super()
helps you access parent class methods.- Commonly used in method overriding and constructors.
- Improves maintainability and supports multiple inheritance.
Practice Problem
Create a class Vehicle
with a method start()
. Then create a class Car
that inherits from Vehicle
and overrides start()
, but still calls Vehicle.start()
using super()
.
class Vehicle:
def start(self):
print("Vehicle started")
class Car(Vehicle):
def start(self):
super().start()
print("Car started")
c = Car()
c.start()
Expected Output:
Vehicle started
Car started