Object-oriented programming · lesson 9 of 17
Parts in this lesson
Aitem.loan_days()one call, each object answers
Bfor item in items:one loop, many kinds
Cdef lend_all(items):code that knows only the parent
Dcan_lend()a promise the parent makes, and every child keeps

Polymorphism through overriding

Last updated

A library lends books for 21 days, DVDs for 7 and magazines for 14. You could write an if for each kind of item, everywhere the loan period matters. Or you could ask each item, and let each class give its own answer. That second way is polymorphism, the third idea of OOP. In this lesson one loop lends every kind of item, you write code that knows only the parent class, and you meet the rule every child class has to keep: it must work wherever its parent does.

By the end of this lesson you can

  • Call the same method on objects of different classes, and say which method runs
  • Replace an if/elif chain on the kind of object with a method each class overrides
  • Write a function that uses only what the parent class promises
  • Explain the substitution rule, and spot a child class that breaks it

One call, three answers

Here's the family of items from lesson 4.6, cut down to what this lesson needs. LibraryItem has a loan_days() method, and Book and DVD override it. Magazine doesn't, so it keeps its parent's. The other attributes from 4.5, like a book's author, are left out to keep the examples short.

One parent, three children, one method each writes
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

Line 30 is one line of code, and it runs three times. Each time, item.loan_days() asks Python to find loan_days starting from that object's own class:

  • For Dune, Python finds Book.loan_days on line 11, and gets 21.
  • For Rivers of Ice, it finds DVD.loan_days on line 16, and gets 7.
  • Magazine has no loan_days of its own, so for Garden Monthly Python goes on to the parent and finds LibraryItem.loan_days on line 6.

The same call gives a different answer depending on which object it's made on. That's polymorphism, from the Greek for "many shapes": one call, and each kind of object answers in its own way. You've used it since Stage 1 without the name: len() works on text, lists and dicts, and each one counts in its own way.

Instead of asking what kind it is

Without overriding, the loan period would have to be worked out from the outside. Here's that way, with isinstance from lesson 4.5:

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

It prints the right answers. The trouble starts when the library grows:

  • Every new kind of item means finding this function and adding an elif. And loan_days won't be the only one: the fine, the receipt and the search page would each have a chain like it.
  • The order matters. If a child of Book gets a different period, its elif has to come before Book's on line 16, or isinstance(item, Book) catches it first.

In step 1, the loop on line 29 never asks what kind of item it has. What's true about DVDs lives in DVD. To add a new kind of item, you write one new class, and the loop doesn't change. Try it: add a class Map(LibraryItem) to the step 1 example with its own loan_days of 3, put Map("Old Roads", 1950) in the list, and run it.

When you see a chain of isinstance checks deciding what to do, ask whether each class should answer for itself.

Writing code against the parent

lend_all on line 29 lends a list of items. It's written knowing only what LibraryItem has: a title, and a lend() method that gives back the number of days.

Step 3 code main.py
Edit the code, then run it again
  • Book has an author, but lend_all never reads it. A DVD has no author, and lend_all has to work for every item.
  • Line 31 calls item.lend(). Only LibraryItem defines lend (line 10), so every item runs that same method. But inside it, line 12 calls self.loan_days(), and self is the book or the DVD. So the parent's code still gets each child's own answer.

This is writing code against the parent: a function that uses only what the parent class has will work for every child, including ones nobody has written yet. When you write a function like lend_all, ask which class it really needs, and use only what that class promises.

The substitution rule

Writing code against the parent only works if every child keeps the parent's promises. That's the substitution rule: anywhere your program uses a parent object, you can put a child object instead, and the program still works. Programmers also call it the Liskov substitution principle, after Barbara Liskov, who wrote it down in 1987.

Python doesn't check this rule. Overriding lets a child do anything. It's up to you to keep to it:

What a child's method must keep
An overriding method keeps…
The parametersTakes the same values, so a call written for the parent still works (the wrong way in lesson 4.6)
What it gives backThe same kind of value: loan_days() gives a whole number of days, never text like "a week"
ErrorsNo new errors that code written for the parent wouldn’t expect
How it does itFree to change: that’s the point of overriding

A child may change how a method works. It mustn't change what the method promises: what it takes, what it gives back, and what can go wrong. The next step shows what happens when a child breaks the last of these.

A reference book breaks the loop

A reference book, like an atlas, stays in the library. So someone writes a ReferenceBook whose lend() raises NotAvailable, the error from lesson 4.8. lend_all hasn't changed, and it has worked for every item so far. Run it.

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

Dune is lent, then the program stops on line 24, inside ReferenceBook.lend, and Emma is never lent at all. Read the traceback from the bottom up: line 24 raised the error, and line 29 is where lend_all called it.

Nothing is wrong with lend_all. It was written against LibraryItem, whose lend() always gives back a number of days. ReferenceBook broke that promise, so it can't stand in for its parent. Every loop that lends items is now broken, though none of them changed.

The fix is to make the parent's promise say what's really true: not every item can be lent. The parent gets a can_lend() method that says yes, ReferenceBook overrides it to say no, and code that lends asks first.

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

Every item now keeps the parent's promise, including the reference book, and the loop works for all three. Another fix fits a library where lending can already fail, for example because the item is out (lesson 4.8). Then the parent's lend() raising NotAvailable is part of its promise, and lend_all should catch it with except NotAvailable. Either way, the parent says what can happen, and every child keeps to it.

In other languages

This step is optional. It's for anyone who will meet Java, C# or Rust later.

Polymorphism through a shared parent
PythonJava and C#Rust
One call, many kindsAny object with the method, found when the call runsObjects of one parent class or interface, checked when compilingA trait, through generics or trait objects (dyn Trait), checked when compiling
A list of mixed items[Book(...), DVD(...)]: any listList<LibraryItem>: the list names the parentVec<Box<dyn Item>>: the list names the trait
Overriding a methodWrite it again in the childJava: write it again, with @Override to have it checked. C#: the parent says virtual, the child says overrideNo inheritance: each type writes the trait’s method

In Java and C#, a list of LibraryItem can only hold objects whose class says it is a LibraryItem, and calling a method the parent doesn't have is caught before the program runs. Python finds the method when the call runs, so a mistake only shows up then. None of the three checks the substitution rule for you. Rust has no inheritance. Simple Rust 4.3 shows the trait that takes its place, and later lessons of Simple Rust cover generics and trait objects.

Check what you learned

Three questions. Pick an answer, then check it.

What does this program print?
class Item:
    def kind(self):
        return "item"


class Map(Item):
    def kind(self):
        return "map"


class Atlas(Map):
    pass


print(Atlas().kind())
Code all over the program calls item.loan_days() and adds the answer to a date. Which new child class keeps the substitution rule?
Why is a loan_days() method in each class better than one function with an isinstance check for each kind of item?

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