In Python, the super() function is used to call a method from the parent (base) class inside a subclass. It is commonly used in inheritance to reuse code from the parent class, such as constructors (__init__) or overridden methods, while still allowing the subclass to extend or modify behavior.
Key Points #
- Access parent methods: Allows the subclass to invoke methods defined in the parent class.
- Avoids explicitly naming the parent: Makes code maintainable if the parent class name changes.
- Supports multiple inheritance: Works correctly with Python’s Method Resolution Order (MRO).
Example 1: Using super() in Constructor #
filename.python
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class Manager(Employee):
def __init__(self, name, salary, department):
super().__init__(name, salary) # Call parent constructor
self.department = department
mgr = Manager("Kumar", 10000, "IT")
print(mgr.name) # Kumar
print(mgr.salary) # 10000
print(mgr.department) # IT
Here, super().init(name, salary) ensures that the Employee constructor runs, so name and salary are initialized without duplicating code.
Example 2: Using super() to Call Overridden Methods
filename.python
class Employee:
def work(self):
print("Employee working")
class Manager(Employee):
def work(self):
super().work() # Call parent method
print("Manager managing team")
mgr = Manager()
mgr.work()
# Output:
# Employee working
# Manager managing team
super().work()calls the parent class method, and then the subclass adds extra behavior.
Advantages #
- Promotes code reuse and avoids duplication.
- Makes maintenance easier—no need to hardcode parent class names.
- Supports multiple inheritance using Python’s MRO.
Common Use Cases #
- Calling the parent constructor (
__init__) to initialize shared attributes. - Accessing overridden methods to extend their functionality.
- Ensuring proper initialization in complex multiple inheritance scenarios.
In practical projects, I used super() in a reporting system:
- Base class
Reporthad a__init__method to set common attributes liketitleanddate. - Subclasses
MonthlyReportandAnnualReportusedsuper().__init__()to initialize common data, then added report-specific attributes. - This avoided code duplication and made the system scalable for additional report types.
