Object-oriented programming · lesson 6 of 17
Parts in this lesson
Adef loan_days(self):override: the child's own version
Bsuper().describe()extend: the parent's, then more
Creturn NotImplemented"I can't compare with that"
Dclass Shelf(list):a built-in as the parent
Esuper().__init__4.5: run the parent's set-up

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 list or Exception

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.

Each child writes its own version of the parent’s method
100%
LibraryItem
  • +title: str
  • +year: int
  • +__init__(title: str, year: int)
  • +loan_days(): int
Book
  • +loan_days(): int
DVD
  • +loan_days(): int
Magazine
  • 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.
Step 1 code main.py
Edit the code, then run it again
  • 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.
  • Magazine writes 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.

Step 2 code main.py
Edit the code, then run it again
  • Line 16: Book.describe() gets Dune (1965) from the parent and adds by Frank Herbert.
  • Line 25: DVD.describe() adds the running time instead.
  • Line 30: a plain LibraryItem still 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.

Two ways to change a parent's method
HowWhat runsExample
OverrideWrite a method with the same name in the childThe child’s version runs instead of the parent’sDVD.loan_days()
ExtendOverride, and call super().method() insideThe parent’s version runs, then the child adds to itBook.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:

  1. The object's own attributes, as in lesson 3.4.
  2. The object's class.
  3. 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.

Step 3 code main.py
Edit the code, then run it again

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().

Step 4 code main.py
Edit the code, then run it again
  • Lines 6 and 7 override object's __str__. Lines 20 and 21 extend it for books, so print(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. Book inherits that, so line 27 prints True.

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.

Step 5 code main.py
Edit the code, then run it again
  • Lines 1 and 2 make a new kind of error. pass is enough: it inherits everything it needs, including keeping the message.
  • Line 5 makes Shelf a child of list. 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 Shelf inherited list'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.

Step 6 code main.py
Edit the code, then run it again

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.

Overriding in three languages
PythonJavaRust
OverridingWrite a method with the same nameThe same, usually marked @Override so the compiler checks there’s a parent method to overrideNo parent. A type writes its own version of a trait’s method, replacing the trait’s default
Calling the parent’s versionsuper().describe()super.describe()No parent to call
An override with different parametersAllowed. It breaks when the parent’s code calls itIt’s a new method, not an override. @Override turns that into a compile errorWon’t compile: it must match the trait exactly
Stopping a method being overriddenNothing stops itfinalDoesn’t arise
Your own error typeclass NotAvailable(Exception):class NotAvailable extends ExceptionAn 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.

What does this program print?
class LibraryItem:
    def loan_days(self):
        return 14

    def label(self):
        return f"{self.loan_days()} days"


class DVD(LibraryItem):
    def loan_days(self):
        return 7


print(DVD().label())
Book.describe() should give the parent's description with the author added. Which line goes inside it?
A parent has def fine(self):. A child overrides it with def fine(self, days):. What happens when the parent's code calls self.fine() on a child object?

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.

All sources for Simple Python