🔁 What is Method Overriding in Python?
Method Overriding is an object-oriented programming feature where a subclass provides a specific implementation of a method that is already defined in its parent class.
This allows a child class to modify or extend the behavior of its superclass.
📘 Why Override Methods?
- To change or customize the behavior of a parent class method.
- To implement polymorphism.
- To extend parent class functionality.
🔧 Example: Basic Method Overriding
class Animal:
def speak(self):
return "Animal speaks"
class Dog(Animal):
def speak(self):
return "Dog barks"
# Testing
a = Animal()
d = Dog()
print(a.speak()) # Output: Animal speaks
print(d.speak()) # Output: Dog barks
🧠 Explanation
Dogclass inheritsAnimal.speak()method inDogoverrides the one inAnimal.- Each class defines its own version of
speak().
🛠 Calling Parent Method from Child
You can still access the parent method using super().
class Bird:
def sound(self):
return "Chirp"
class Parrot(Bird):
def sound(self):
return super().sound() + " and talks too"
p = Parrot()
print(p.sound()) # Output: Chirp and talks too
✅ Summary
- Method Overriding lets you redefine a method in a subclass.
- Enhances flexibility and supports polymorphism.
super()can be used to include parent class functionality.
Mastering method overriding is key to building extensible and well-structured OOP designs in Python. 🧩