Method overriding in Python allows a subclass to provide a specific implementation of a method that is already defined in its parent class. It is a key feature of object-oriented programming and enables polymorphism, which allows you to use the same method name in different classes with unique behaviors.
In this example, we create a parent class Animal with a method speak(). The subclass Dog overrides the speak() method to provide a specific implementation.
class Animal: def speak(self): return "Animal speaks" class Dog(Animal): def speak(self): return "Dog barks" # Example usage animal = Animal() dog = Dog() print(animal.speak()) # Output: Animal speaks print(dog.speak()) # Output: Dog barks
In this example, the subclass calls the parent class method using super() and adds additional behavior to it.
class Animal: def speak(self): return "Animal speaks" class Cat(Animal): def speak(self): original_speak = super().speak() return f"{original_speak} and Cat meows" # Example usage cat = Cat() print(cat.speak()) # Output: Animal speaks and Cat meows
Constructors (__init__ methods) can also be overridden in subclasses. Here's an example:
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("Sparrow", True) print(bird.name) # Output: Sparrow print(bird.can_fly) # Output: True
Method overriding is a powerful feature in Python that promotes code reuse and enables polymorphism. It is widely used in object-oriented programming to implement specific behaviors in subclasses while maintaining a common interface in the parent class.