๐ 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
Dog
class inheritsAnimal
.speak()
method inDog
overrides 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. ๐งฉ