CodeBlanks Logo Icon CodeBlanks

Method overriding

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

main.py
# Define the Animal and Dog classes

Sample solution

main.py
# 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

Question
class Dog(Animal):
    def speak(self):
        print(____)
Answer
class Dog(Animal):
    def speak(self):
        print("Woof")

Explanation: Dog.speak prints "Woof"; it overrides the parent.

All lessons in Intermediate