Sub topic 3
Overriding a method in a subclass
This chapter assumes you can define a class, create instances, and write methods that use self. It also assumes you have seen a subclass written as class Dog(Animal):. It covers how a subclass replaces inherited behavior and what happens when you do. It also covers the mistakes that cause bugs. Calling the parent's version with super() is the next chapter's topic.
What overriding means
A subclass overrides a method when it defines a method with the same name as one in a parent class. Instances of the subclass then use the subclass's version. Instances of the parent keep the original.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def speak(self):
return f"{self.name} barks"
class Cat(Animal):
pass
for pet in (Animal("Generic"), Dog("Rex"), Cat("Tom")):
print(pet.speak())The output is:
Generic makes a sound
Rex barks
Tom makes a soundDog overrides speak(). Cat does not, so it inherits Animal.speak() unchanged. Neither subclass defines __init__, so both inherit it. The override affects only Dog. Animal and Cat are untouched.
Why the override wins
Python looks for a name on the instance first. Then it searches the instance's class, then each parent class in order, and it stops at the first match. The subclass is searched before its parent, so a method defined on the subclass hides the parent's method of the same name. This is called shadowing. The parent's method still exists, and Python just never reaches it through a Dog instance.
The chapter on attribute lookup covers the search order in detail. For now, remember that the first match wins and subclasses are checked before parents.
Overriding changes behavior everywhere, including inside parent code
Overriding works even when the call comes from a method the subclass never touched. When a parent method calls self.something(), Python looks something up on the actual object. If the object belongs to a subclass, the subclass's override runs.
class Report:
def render(self):
return f"{self.title()}\n{self.body()}"
def title(self):
return "Report"
def body(self):
return "(empty)"
class SalesReport(Report):
def title(self):
return "Sales"
print(SalesReport().render())The output is:
Sales
(empty)SalesReport never defines render(). It inherits Report.render(), which calls self.title(). Because self is a SalesReport, the override runs. Designs that rely on this are called template methods. The parent fixes the overall steps, and subclasses override the hooks. The consequence is that renaming or changing a parent method can break subclasses you cannot see from the parent's code.
Overriding data attributes
Class attributes can be overridden the same way, and methods that read them through self pick up the override.
class Animal:
sound = "..."
def speak(self):
return f"{type(self).__name__} says {self.sound}"
class Dog(Animal):
sound = "Woof"
print(Animal().speak()) # Animal says ...
print(Dog().speak()) # Dog says Woof
rex = Dog()
rex.sound = "Grr" # shadows the class attribute on this instance only
print(rex.speak()) # Dog says Grr
print(Dog().speak()) # Dog says WoofAssigning rex.sound creates an instance attribute. It wins over the class attribute for rex only. Other Dog objects and the class itself are unchanged.
What you can and cannot override
Any name can be overridden, because Python treats methods as ordinary class attributes. In practice, these categories come up most often.
| Kind of name | Example | Notes |
|---|---|---|
| Regular method | `speak()` | The common case. |
| Special method | `__str__`, `__repr__`, `__eq__` | Overridden the same way. Python calls them through the type. |
| Class attribute | `sound = "Woof"` | Methods that read `self.sound` see the override. |
| Property | `@property def label` | Override with another property of the same name. |
| Name-mangled name | `__helper` | Not overridable in the usual way. See below. |
Special methods follow the same rule. object supplies default __repr__ and __eq__, and your class overrides them by defining its own.
class Animal:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Animal({self.name!r})"
class Dog(Animal):
def __repr__(self):
return f"Dog({self.name!r})"
print([Animal("a"), Dog("b")]) # [Animal('a'), Dog('b')]No overloading by signature
Python does not choose a method by its parameter list. A name maps to one function, so defining speak(self, loud) in a subclass replaces speak(self) outright. It does not add a second variant. The override can then break code that calls the method the old way.
class Shape:
def area(self):
return 0
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self, precision):
return round(3.14159 * self.r ** 2, precision)
def total(shapes):
return sum(s.area() for s in shapes)
try:
total([Circle(1)])
except TypeError as exc:
print("TypeError:", exc)Python never checks that an override's signature matches the parent's. The error appears only when a caller uses the parent's calling convention. Give new parameters defaults (precision=2) so the override still accepts every call the parent accepted. The chapter on substitutability explains the principle behind this.
Gotcha: typos create new methods, not overrides
If you misspell the name, Python creates a new method and the parent's version keeps running. No error is raised.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speek(self): # typo: this is a brand-new method
return "Woof"
print(Dog().speak()) # prints "..." instead of "Woof"Python 3.12 added the typing.override decorator. Marking a method with @override tells a static type checker such as mypy or pyright to report an error if no parent method has that name. The decorator does not enforce anything when the program runs, so you need a type checker for it to help.
from typing import override
class Animal:
def speak(self):
return "..."
class Dog(Animal):
@override
def speak(self):
return "Woof"
print(Dog().speak()) # WoofOn Python 3.11 and earlier, override is available from the typing_extensions package.
Gotcha: double-underscore names are not overridden
A name that starts with two underscores and does not end with two underscores is name-mangled. Python rewrites __step inside class Base to _Base__step. A subclass's __step becomes _Child__step, which is a different name, so it does not override anything.
class Base:
def run(self):
return self.__step()
def __step(self):
return "base"
class Child(Base):
def __step(self):
return "child"
print(Child().run()) # baserun() calls self._Base__step(), and Child defines _Child__step, so the base version runs. Use a single underscore (_step) for helpers that subclasses may override.
Reaching the parent version
Sometimes you want the parent's behavior as well, or only on certain paths. You can name the parent class and pass the instance yourself.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
rex = Dog()
print(rex.speak()) # Woof
print(Animal.speak(rex)) # ...This hard-codes the parent's name, and it behaves badly once multiple inheritance is involved. The next chapter introduces super(), which is the usual way to do this.
Checklist for a safe override
- Spell the name exactly as in the parent, and use
@overridewith a type checker where you can. - Accept at least the parameters the parent accepts, and give any new parameters defaults.
- Return a value of the same kind the parent returns, so callers do not need to know which class they have.
- Use a single underscore for helper methods that subclasses are meant to override.
- Test the subclass through the parent's interface, for example by calling
render()on aSalesReport.
Exercise
Given the code below, what does print(Pup().speak()) print, and why?
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
class Pup(Dog):
pass
Show answer
It prints "Woof". Pup defines no speak, so lookup moves to its parent Dog, where speak is found and used. The search stops there, and Animal.speak is never reached.
Exercise
A class Base has def run(self): return self._greet() and def _greet(self): return "hi". A subclass Loud(Base) defines def _greet(self): return "HI". What does Loud().run() return? What changes if both methods are renamed to __greet?
Show answer
With the single underscore, Loud().run() returns "HI". run() calls self._greet(), and self is a Loud, so the override runs. With __greet, name mangling turns the call inside Base into self._Base__greet(). Loud defines _Loud__greet, which is a different name. The call returns "hi", and the subclass method is never used.