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/elifchain 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.
- +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.
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_dayson line 11, and gets 21. - For Rivers of Ice, it finds
DVD.loan_dayson line 16, and gets 7. Magazinehas noloan_daysof its own, so for Garden Monthly Python goes on to the parent and findsLibraryItem.loan_dayson 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:
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. Andloan_dayswon'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
Bookgets a different period, itselifhas to come beforeBook's on line 16, orisinstance(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.
Bookhas anauthor, butlend_allnever reads it. A DVD has no author, andlend_allhas to work for every item.- Line 31 calls
item.lend(). OnlyLibraryItemdefineslend(line 10), so every item runs that same method. But inside it, line 12 callsself.loan_days(), andselfis 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:
| An overriding method keeps… | |
|---|---|
| The parameters | Takes the same values, so a call written for the parent still works (the wrong way in lesson 4.6) |
| What it gives back | The same kind of value: loan_days() gives a whole number of days, never text like "a week" |
| Errors | No new errors that code written for the parent wouldn’t expect |
| How it does it | Free 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.
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.
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.
| Python | Java and C# | Rust | |
|---|---|---|---|
| One call, many kinds | Any object with the method, found when the call runs | Objects of one parent class or interface, checked when compiling | A trait, through generics or trait objects (dyn Trait), checked when compiling |
| A list of mixed items | [Book(...), DVD(...)]: any list | List<LibraryItem>: the list names the parent | Vec<Box<dyn Item>>: the list names the trait |
| Overriding a method | Write it again in the child | Java: write it again, with @Override to have it checked. C#: the parent says virtual, the child says override | No 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.
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: derived classes may override methods of their base classes
- The Python Tutorial: Odds and Ends: code that expects one kind of object can often be passed another with the same methods
- Built-in Functions: isinstance
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow
- Barbara Liskov and Jeannette Wing: A Behavioral Notion of Subtyping (1994): the substitution rule: a child must work wherever its parent does
- The Java Tutorials: Polymorphism: overriding through a shared parent in Java
- C# documentation: Polymorphism: virtual and override in C#
- The Rust Programming Language: Using Trait Objects to Abstract over Shared Behavior: a list of different types behind one trait in Rust