Method Overriding
In Python, method overriding happens when a child class defines a method that already exists in its parent class, but it changes (or overrides) how the method works. Think of it like this:
- The parent class provides a general way of doing something.
- The child class wants to do the same thing, but in a different or more specific way.
By overriding a method, the child class "replaces" the parent class’s method with its own version.
Why use method overriding?
- Customization: Allows the child class to change how a method works without changing the parent class.
- Specialization: Gives the child class more specific behavior while still inheriting general features from the parent class.
- Flexibility: You can extend or improve functionality in the child class based on your needs.
How does method overriding work in Python?
Parent class
Let’s start with a parent class that has a method.
class Animal:
def speak(self):
return "I make a sound"
Child class
Now, the child class inherits from the Animal
speak()
class Dog(Animal):
def speak(self):
return "Woof!"
Using the classes
Now, when we create an instance of Dog
speak()
Animal
# Create a Dog object
dog = Dog()
# Call speak method
print(dog.speak()) # Output: Woof! (This is the overridden method)
If we created an Animal
speak()
# Create an Animal object
animal = Animal()
# Call speak method
print(animal.speak()) # Output: I make a sound
Key points to remember:
-
The child class overrides the method in the parent class by defining its own version of the method.
- The parent class method is still available if needed, but the child class version will be used when called on an object of the child class.
- You don’t need to call the parent method in the child class unless you want to use it and extend it (using
).super()
Real-world analogy
Think of a parent class as a general job description:
- Example: A job title of "Employee" might have a method called
, which just means "do work".work()
A child class is a more specific version of that job:
- Example: "Engineer" is a child of "Employee", and engineers override the
work()