Overriding and extending
Last updated
A child class gets everything its parent has. But a DVD isn't lent for as long as a book, and a book's description should name its author. In this lesson you'll replace a parent's method in a child, add to a parent's method instead of replacing it, follow the path Python takes to find a method, write your own __str__ and __eq__ in a family of classes, and build on Python's own classes, list and Exception.
By the end of this lesson you can
- Override a parent's method, and extend it with
super() - Say which class's method runs, by following the child first, then the parent
- Override
__str__and__eq__in a family of classes - Build a class on
listorException
Overriding a method
Most items are lent for 14 days, so LibraryItem has a loan_days() method that says so. But books go out for 21 days and DVDs for 7. Each of those classes writes a method with the same name, and its own answer. Writing a method a parent already has is called overriding it.
- +title: str
- +year: int
- +__init__(title: str, year: int)
- +loan_days(): int
- +loan_days(): int
- +loan_days(): int
- Class LibraryItem; attributes: title, year; methods: __init__, loan_days.
- Class Book; inherits from LibraryItem; no attributes of its own; methods: loan_days.
- Class DVD; inherits from LibraryItem; no attributes of its own; methods: loan_days.
- Class Magazine; inherits from LibraryItem; no attributes of its own; no methods of its own.
- Lines 6 and 7: the parent's version, the default for every item.
- Lines 11 and 12:
Book's own version. A book never uses the parent's. - Lines 16 and 17: the same for
DVD. Magazinewrites nothing, so it inherits the parent's 14 days.
Line 30 makes the same call, item.loan_days(), on three kinds of item, and each one answers for itself. The loop doesn't need to know which kind of item it has. That's a first look at polymorphism, which has its own lessons later in this stage.
Extending with super()
Sometimes a child doesn't want to replace the parent's method, only to add to it. A book's description is the item's description with the author on the end. Inside the override, super().describe() runs the parent's version and gives back what it returned. This is called extending a method.
- Line 16:
Book.describe()getsDune (1965)from the parent and addsby Frank Herbert. - Line 25:
DVD.describe()adds the running time instead. - Line 30: a plain
LibraryItemstill uses the parent's version.
You've been extending since lesson 4.5: every __init__ that calls super().__init__ and then sets one more attribute is extending its parent's __init__. The title and year are formatted in one place, line 7. Change it to {self.title}, {self.year} and run it: both children change with it.
| How | What runs | Example | |
|---|---|---|---|
| Override | Write a method with the same name in the child | The child’s version runs instead of the parent’s | DVD.loan_days() |
| Extend | Override, and call super().method() inside | The parent’s version runs, then the child adds to it | Book.describe(), and every __init__ with super().__init__ |
How Python finds a method
When you call atlas.label(), Python has to find a method called label. It looks in this order, and stops at the first one it finds:
- The object's own attributes, as in lesson 3.4.
- The object's class.
- That class's parent, then its parent, and so on up to
object.
A ReferenceBook is a Book that can't be taken home: it's read in the library. So its loan_days() is 0.
Line 24 calls atlas.label(). Lines 26 and 27 show the search: label isn't in atlas, nor in ReferenceBook, nor in Book. Python finds it in LibraryItem.
Now look at line 10, inside label(). It calls self.loan_days(), and self is still atlas. So the search starts again from atlas's own class, finds ReferenceBook's version first, and gets 0. The parent's code called the child's method, without knowing the child exists. That's what makes overriding useful: a parent can write the steps once, and each child fills in its own details.
Overriding __str__ and __eq__
__str__ and __eq__ are methods like any other. Lesson 4.5 showed every class inherits plain versions of them from object. Writing your own in lesson 3.5 was overriding them. In a family of classes, a child can extend the parent's version with super().
- Lines 6 and 7 override
object's__str__. Lines 20 and 21 extend it for books, soprint(dune)on line 25 shows the author too, and so does the f-string on line 26. - Lines 9 to 12 override
object's__eq__, so two items with the same title and year are equal.Bookinherits that, so line 27 printsTrue.
Line 28 compares a book with some text. Text has no title, so other.title on line 12 would stop the program. Lines 10 and 11 check first. When other isn't a library item, __eq__ returns NotImplemented: a special value that means "I don't know how to compare with that". Python then asks the other side. Text doesn't know how to compare itself with a book either, so == gives False, and != on line 29 gives True.
Delete lines 10 and 11 and run it again to see the AttributeError they prevent.
Building on list and Exception
Python's own classes can be parents too. A Shelf that's a list with one extra method gets everything a list can do for free: append, len, in, square brackets and the rest.
And every error is a class. ValueError and KeyError are children of Exception. Build on Exception and you have an error of your own, which raise and except work with like any other.
- Lines 1 and 2 make a new kind of error.
passis enough: it inherits everything it needs, including keeping the message. - Line 5 makes
Shelfa child oflist. Line 13 makes one from a list, and lines 14 and 15 use what it inherited. - Lines 6 to 10 add a method. It raises the new error when the title isn't there.
- Line 17 prints like a list, because
Shelfinheritedlist's__repr__. - Lines 18 to 21 catch the new error by its own name.
Building on Exception is common: lesson 4.8 makes a whole family of library errors. Building on list or dict is rarer. Their methods don't always call each other the way you'd expect, so overriding one doesn't change the others. Holding a list in an attribute, as Member did in lesson 3.3, is often the safer choice.
An override that takes different values
Someone wants new DVDs lent for only 3 days, so they give DVD.loan_days() a value to say whether the DVD is new. Press Run and read the error from the bottom up.
The last line says loan_days() is missing a value called new_release. The call that's missing it is on line 10, in the parent's due_day(). That code calls self.loan_days() the parent's way, with nothing in the brackets. As step 3 showed, it finds the child's version, which needs one value more.
The parent's code doesn't know about the change, and it shouldn't have to. An override has to work everywhere the parent's method works, so it must accept every call the parent's version accepts.
To fix it, give the new parameter a default, so the old way of calling still works. Change line 14 to def loan_days(self, new_release=False):. Then rivers.loan_days() gives 7, and rivers.loan_days(True) gives 3.
In other languages
This step is optional. It's for anyone who will meet Java or Rust later.
| Python | Java | Rust | |
|---|---|---|---|
| Overriding | Write a method with the same name | The same, usually marked @Override so the compiler checks there’s a parent method to override | No parent. A type writes its own version of a trait’s method, replacing the trait’s default |
| Calling the parent’s version | super().describe() | super.describe() | No parent to call |
| An override with different parameters | Allowed. It breaks when the parent’s code calls it | It’s a new method, not an override. @Override turns that into a compile error | Won’t compile: it must match the trait exactly |
| Stopping a method being overridden | Nothing stops it | final | Doesn’t arise |
| Your own error type | class NotAvailable(Exception): | class NotAvailable extends Exception | An enum or struct that implements the Error trait |
C# is stricter than both Python and Java. A method can only be overridden if the parent marks it virtual, and the child has to write override. Calling the parent's version is base.Describe().
Rust has no parents, but a trait can give a method a default body, which a type can replace with its own. Simple Rust 4.3 shows how.
Check what you learned
Three questions. Pick or type an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Tutorial: Inheritance: overriding, and calling the base class's method
- Built-in Functions: super
- The Python Language Reference: object.__eq__: returning NotImplemented
- The Python Tutorial: User-defined Exceptions
- Built-in Exceptions: Exception: the parent class for your own errors
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- The Java Tutorials: Overriding and Hiding Methods: overriding in Java, and @Override
- The Java Tutorials: Writing Final Classes and Methods: stopping a method being overridden
- The Java Tutorials: Creating Exception Classes: your own error type in Java
- The Rust Programming Language: Default Implementations: a Rust trait method a type can replace