Method overriding in Python occurs when a child (subclass) provides a new implementation of a method that is already defined in its parent (superclass). The child’s version replaces the parent’s version when called using a child object. This is a key concept of polymorphism in object-oriented programming.
Key Points #
- Same method name, same parameters as in the parent class.
- Allows child classes to provide specific behavior while reusing the parent class structure.
- Supports runtime polymorphism, as the method called depends on the object type.
Example #
class Employee:
def work(self):
print("Employee is working.")
class Manager(Employee):
def work(self): # Method overriding
print("Manager is managing the team.")
emp = Employee()
mgr = Manager()
emp.work() # Output: Employee is working.
mgr.work() # Output: Manager is managing the team.
Here:
Employeedefineswork().Manageroverrideswork()to provide behavior specific to managers.
Accessing the Parent Method #
Sometimes you want to extend the parent method instead of completely replacing it. You can use super():
class Manager(Employee):
def work(self):
super().work() # Call parent method
print("Manager is also preparing reports.")
mgr = Manager()
mgr.work()
# Output:
# Employee is working.
# Manager is also preparing reports.
Difference Between Overloading and Overriding #
| Feature | Method Overloading | Method Overriding |
|---|---|---|
| Number of methods | Same name, different parameters | Same name, same parameters |
| Occurs in | Same class | Parent & child class |
| Polymorphism type | Compile-time (simulated in Python) | Runtime |
| Purpose | Handle different inputs | Provide child-specific behavior |
Practical Use Case #
I used method overriding in a reporting system:
- Base class:
Reporthad a genericgenerate()method. - Subclasses:
MonthlyReportandAnnualReportoverrodegenerate()to handle specific report formats.
This allowed a consistent interface (generate()) while enabling customized behavior for different report types, making the system modular and scalable.
