Method overriding
- Python course
- Intermediate
- Lesson 9/116
- 4 min
Learn to override methods in derived classes.
Method overriding
Overriding is when a child class redefines a parent method with the same name. When an instance of the child calls the method, the child version runs.
Example: class Animal:\n def speak(self):\n print("Sound") and class Dog(Animal):\n def speak(self):\n print("Woof"). The call d = Dog(); d.speak() prints Woof. The parent version is hidden but can still be called via super().speak().
Child first
When you call a method, Python looks at the child first; if not found, it goes up to the parent. So a same-name method in the child replaces the parent's.
Example: if Dog has speak, d.speak() calls it. A method not in Dog (e.g. sleep) is searched in the parent. This mechanism is called method resolution; the order matters in multiple inheritance.
Practice Override with Dog.speak
First define the Animal class; add def speak(self): and in the body write print("Sound"). Then define class Dog(Animal):; add def speak(self): and in the body write print("Woof"). Then call d = Dog() and d.speak().
Starter code
# Define the Animal and Dog classesSample solution
# Define the Animal and Dog classes
class Animal:
def speak(self):
print("Sound")
class Dog(Animal):
def speak(self):
print("Woof")
d = Dog()
d.speak()Expected output
Woof
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the override concepts
| Term | Meaning |
|---|---|
Animal.speak |
Parent method |
Dog.speak |
Child method |
d.speak() |
Child version runs |
2 What does overriding mean?
- A child class redefining a parent method Correct answer
- To call the parent method
- To delete a method
- To merge two methods
Explanation: Overriding is the child redefining a method with the same name.
3 Complete the override body
class Dog(Animal):
def speak(self):
print(____)
class Dog(Animal):
def speak(self):
print("Woof")
Explanation: Dog.speak prints "Woof"; it overrides the parent.