Skip to content

Module 11 · Object-Oriented Programming — topic 19 of 25

Method overriding

Replacing or extending a parent's method in a subclass: full replacement, extension with super(), overriding special methods like __str__, and the template-method pattern.

Beginner 10 min read·Lesson 176 of 306 in Python Programming

Learning objectives

  • Override methods to change behaviour
  • Extend instead of replace using super()
  • Use the template-method pattern

Definition

Method overriding is defining a method in a subclass with the same name as a method in its parent. When the method is called on a subclass instance, the subclass's version runs instead of the parent's.

Introduction

Every animal speaks, but each speaks differently. The parent class provides the general method; each subclass overrides it with the right behaviour.

Why it matters

Overriding is how subclasses specialise their parents. It is the mechanism behind polymorphism: the same call does the right thing for each type.

Detailed explanation

Define a method with the same name in the subclass. Python finds it first because the subclass comes first in the MRO.

A full override replaces the parent's behaviour completely.

An extending override calls super().method(...) and adds to or adjusts the result — often the best choice because the parent's logic isn't duplicated.

Special methods (__str__, __eq__, __len__) are overridden the same way; overriding object.__str__ changes how print shows your objects.

The template-method pattern: a parent method defines the overall steps and calls 'hook' methods; subclasses override just the hooks.

Keep the same parameters and return type as the parent so code written for the parent works with any subclass.

Syntax

Python
class Animal:
def sound(self):
return "..."
class Dog(Animal):
def sound(self): # overrides Animal.sound
return "Woof"
  • Same name in the subclass overrides.
  • super().method() reuses the parent's version.
  • Keep the same signature.

Code examples

Each subclass overrides one method

Python
class Animal:
def sound(self):
return "..."
def speak(self):
return f"{type(self).__name__} says {self.sound()}"
class Dog(Animal):
def sound(self):
return "Woof"
class Cat(Animal):
def sound(self):
return "Meow"
for a in [Animal(), Dog(), Cat()]:
print(a.speak())
Output
Animal says ...
Dog says Woof
Cat says Meow

Extending __str__ with super()

Python
class Product:
def __init__(self, name, price):
self.name, self.price = name, price
def __str__(self):
return f"{self.name} - Rs {self.price}"
class DiscountedProduct(Product):
def __init__(self, name, price, off):
super().__init__(name, price)
self.off = off
def __str__(self):
return super().__str__() + f" ({self.off}% off)"
print(Product("Pen", 20))
print(DiscountedProduct("Bag", 1200, 15))
Output
Pen - Rs 20
Bag - Rs 1200 (15% off)

More examples

The template-method pattern

Python
class Report:
def render(self, rows):
lines = [self.header()]
lines += [self.row(r) for r in rows]
lines.append(self.footer(rows))
return "\n".join(lines)
def header(self):
return "REPORT"
def row(self, r):
return str(r)
def footer(self, rows):
return f"{len(rows)} rows"
class CsvReport(Report):
def header(self):
return "name,marks"
def row(self, r):
return f"{r[0]},{r[1]}"
def footer(self, rows):
return f"# total {sum(m for _, m in rows)}"
data = [("Asha", 91), ("Ravi", 78)]
print(Report().render(data))
print("---")
print(CsvReport().render(data))
Output
REPORT
('Asha', 91)
('Ravi', 78)
2 rows
---
name,marks
Asha,91
Ravi,78
# total 169

Step-by-step explanation

  • render is written once in Report and fixes the order: header, rows, footer.
  • CsvReport overrides only the three hooks; it inherits render unchanged.
  • When render calls self.header(), Python finds CsvReport's version because self is a CsvReport.

Expected output

Running “The template-method pattern” prints exactly:

TextOutput
REPORT
('Asha', 91)
('Ravi', 78)
2 rows
---
name,marks
Asha,91
Ravi,78
# total 169

Practical applications

  • unittest.TestCase subclasses override setUp and tearDown hooks.
  • HTTP handler classes override do_GET and do_POST.

Best practices

  • Extend with super() when the parent's behaviour is still needed.
  • Keep overriding methods compatible with the parent's signature.
  • Use hook methods to make classes easy to customise.

Common mistakes

Changing the signature

Avoid

class Dog(Animal):
def speak(self, loud): # parent takes no argument

Prefer

def speak(self, loud=False): ...

Code that calls animal.speak() would break for dogs.

Copy-pasting the parent's code

Avoid

def __str__(self):
return f"{self.name} - Rs {self.price} ({self.off}% off)"

Prefer

def __str__(self):
return super().__str__() + f" ({self.off}% off)"

Duplicated logic drifts out of sync when the parent changes.

Important notes

  • Python has no 'override' keyword; typing.override (3.12+) is an optional decorator that type checkers can verify.

Key takeaways

  • A subclass method with the same name overrides the parent's.
  • super() lets you extend instead of replace.
  • Template methods call hooks that subclasses override.

Try it yourself

  1. 1
    Add an HtmlReport subclass to the report example.
  2. 2
    Override __str__ in a Student subclass of Person so it also shows the roll number.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic