Method Overriding in Python: Definition and Examples
method overriding happens when a child class provides its own version of a method that already exists in its parent class. This allows the child class to change or extend the behavior of that method while keeping the same method name.How It Works
Imagine you have a basic recipe for making a sandwich written in a cookbook (the parent class). Now, you want to make a special sandwich with extra ingredients, so you write your own version of the recipe (the child class) that replaces the original one. This is like method overriding in Python.
When a child class defines a method with the same name as one in its parent class, Python uses the child's method instead of the parent's when you call it on the child object. This lets you customize or improve the behavior without changing the original code.
Example
This example shows a parent class Animal with a method sound(). The child class Dog overrides sound() to provide a different message.
class Animal: def sound(self): return "Some generic sound" class Dog(Animal): def sound(self): return "Bark" animal = Animal() dog = Dog() print(animal.sound()) # Calls parent method print(dog.sound()) # Calls overridden child method
When to Use
Use method overriding when you want a child class to behave differently from its parent class for a specific method. This is common in real-world programming when you have a general class and more specific subclasses that need to customize some actions.
For example, in a game, a generic Character class might have a method attack(), but different character types like Wizard or Warrior override it to perform unique attacks.
Key Points
- Method overriding lets a child class replace a parent class method.
- It uses the same method name and parameters.
- It enables customizing or extending behavior in subclasses.
- It is a core part of object-oriented programming and polymorphism.