Method Overriding
What is Method Overriding?
Method overriding is a powerful feature in object-oriented programming that allows a subclass to provide a specific implementation of a method that is already defined in its parent class.
Method Overriding Mechanics
graph TD
A[Method Overriding] --> B[Redefine Parent Method]
A --> C[Maintain Method Signature]
A --> D[Extend or Replace Functionality]
Key Characteristics
Aspect |
Description |
Requirement |
Method Name |
Must be identical to parent method |
Exact match |
Parameters |
Must have same signature |
Same type and number |
Return Type |
Typically similar |
Covariant return allowed |
Basic Method Overriding Example
class Shape:
def calculate_area(self):
return 0
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
## Override parent method
return self.width * self.height
## Demonstration
rect = Rectangle(5, 3)
print(rect.calculate_area()) ## Output: 15
Advanced Overriding Techniques
1. Using super() in Overridden Methods
class Parent:
def display(self):
print("Parent class method")
class Child(Parent):
def display(self):
## Call parent method before adding custom logic
super().display()
print("Child class additional logic")
child = Child()
child.display()
## Output:
## Parent class method
## Child class additional logic
2. Type Checking and Polymorphism
class Animal:
def make_sound(self):
print("Generic animal sound")
class Dog(Animal):
def make_sound(self):
print("Bark!")
class Cat(Animal):
def make_sound(self):
print("Meow!")
## Polymorphic behavior
def animal_sound(animal):
animal.make_sound()
dog = Dog()
cat = Cat()
animal_sound(dog) ## Output: Bark!
animal_sound(cat) ## Output: Meow!
Best Practices for Method Overriding
- Maintain the contract of the parent method
- Use
super()
when you want to extend parent method
- Ensure the overridden method makes logical sense
- Follow the Liskov Substitution Principle
Common Mistakes to Avoid
- Changing method signature
- Completely breaking parent method's intended behavior
- Overriding without understanding the original method's purpose
Method Resolution Order (MRO)
class A:
def method(self):
print("A method")
class B(A):
def method(self):
print("B method")
class C(A):
def method(self):
print("C method")
class D(B, C):
pass
d = D()
d.method() ## Follows Python's Method Resolution Order
LabEx recommends practicing method overriding to understand its nuances and develop more flexible and extensible object-oriented designs.