Method overriding is a feature in Python that allows a subclass to provide a specific implementation of a method that is already defined in its parent class. It enables polymorphism, where the method in the subclass overrides the method in the parent class with the same name and parameters.
In this example, the parent class Animal
has a method speak()
, which is overridden by the subclass Dog
.
class Animal: def speak(self): return "Animal makes a sound" class Dog(Animal): def speak(self): return "Dog barks" # Example usage animal = Animal() dog = Dog() print(animal.speak()) # Output: Animal makes a sound print(dog.speak()) # Output: Dog barks
Sometimes, you might want to override a method but still use the functionality of the parent class's method. This can be done using the super()
function.
class Animal: def speak(self): return "Animal makes a sound" class Cat(Animal): def speak(self): parent_message = super().speak() return f"{parent_message} and Cat meows" # Example usage cat = Cat() print(cat.speak()) # Output: Animal makes a sound and Cat meows
Constructors (__init__
methods) can also be overridden to provide specific initialization behavior for the subclass.
class Animal: def __init__(self, name): self.name = name class Bird(Animal): def __init__(self, name, can_fly): super().__init__(name) self.can_fly = can_fly # Example usage bird = Bird("Parrot", True) print(bird.name) # Output: Parrot print(bird.can_fly) # Output: True
super()
function to call the parent class method if needed.Method overriding is a core concept in object-oriented programming that enables a subclass to customize or extend the behavior of a method defined in its parent class. It ensures flexibility and allows developers to implement polymorphism effectively in their Python programs.