Sub topic 3
Overriding a Method in a Subclass
This chapter assumes you can define classes, create instances, use self, and write functions with arguments. It also assumes you know what a subclass is and that Python looks for a method on the instance's class first, then on its parents.
What overriding means
A subclass overrides a method when it defines a method with the same name as one in its parent class. Python finds the subclass version first, so the parent version is not used for instances of the subclass.
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"
print(Animal("Generic").speak()) # Generic makes a sound
print(Dog("Rex").speak()) # Rex barksDog does not define __init__, so it inherits the one from Animal. It defines speak, so that method replaces the parent's for Dog instances. Animal instances are unaffected, because the parent class is never changed.
Why the subclass version wins
When you write dog.speak(), Python checks the instance, then Dog, then Animal, then object. It stops at the first match. The Dog version is found before the Animal version is reached.
The parent method still exists. You can call it directly with Animal.speak(dog), and the next chapter shows the better way, super().
What you can change when overriding
An override can differ from the parent in several ways:
- It can return a different value, as
Dog.speakdoes. - It can do extra work, such as logging, before or after its result.
- It can call the parent version and modify the result.
- It can raise an error, for example
NotImplementedError, to say that subclasses must provide their own version.
Overriding applies to any method, including special methods such as __str__ and __eq__. It does not apply to attributes set in __init__. Those live on the instance, not the class, so a subclass cannot "override" them without setting them again.
A worked example: overriding a hook
A common use is a parent class that defines a fixed procedure and calls a method that subclasses are expected to replace.
class Report:
def render(self):
return self.header() + "\n" + self.body()
def header(self):
return "== Report =="
def body(self):
return "(no content)"
class SalesReport(Report):
def body(self):
return "Sales rose 4%"
print(Report().render())
print(SalesReport().render())The output is:
== Report ==
(no content)
== Report ==
Sales rose 4%render is inherited and unchanged. Inside it, self.body() looks up body starting from the class of the actual object. For a SalesReport, that is the overridden version. The parent calls code the subclass supplies, and the parent does not need to know the subclass exists.
Common errors
- Misspelled names. If you write
def speek(self)inDog, Python does not complain. You created a new method, andspeakstill runs the parent version. Check the name when an override seems ignored. - Changed signatures. If the parent's
speak(self)takes no arguments and your override requires one, code written for the parent breaks when it receives your subclass. Keep the same parameters, or add only optional ones. - Forgetting to return. An override that prints instead of returning gives callers
None. Match what the parent method returns. - Overriding by accident. A subclass method with a common name such as
updateorrunmay silently replace a parent method that other code depends on. Read the parent class before choosing method names.
class Dog(Animal):
def speek(self): # typo: this is a new method, not an override
return f"{self.name} barks"
print(Dog("Rex").speak()) # Rex makes a soundThis snippet reuses the Animal class from the first example. The typo is the only reason the parent's behavior still shows.
Replacing versus extending
An override that ignores the parent fully replaces the behavior. Often you want to keep the parent's behavior and add to it. That is the job of super(), covered in the next chapter, and it avoids copying the parent's code into the subclass.
Exercise
A class Base has def greet(self): return "hello". A subclass Child(Base) defines def greet(self, name): return f"hello {name}". Code written for Base calls obj.greet() on a Child. What happens, and how would you fix the override?
Show answer
The call raises a TypeError, because Child.greet requires a name argument that the caller does not pass. Fix it by keeping the parent's signature, or by making the new parameter optional, for example def greet(self, name=None), and returning "hello" when name is None.