Object-oriented programming · lesson 13 of 17
Parts in this lesson
Aclass LibraryItem(ABC)can't be made on its own
B@abstractmethodevery child must write it
Cdef get_kind(self)an abstract getter: every child answers
Dself.loan_days()the parent uses what the child writes
Eisinstance(x, Sized)Python's own abstract classes

Abstract base classes

Last updated

Every item in the library is a book, a DVD or a magazine. A plain LibraryItem is only the idea they share, so it should never be made on its own. In this lesson you'll make Python stop that, with an abstract base class: a parent that says which methods every child must write, without writing them itself. You'll see the error you get when a child forgets one, give the parent methods that use the missing ones, and meet the abstract classes Python already has in collections.abc.

By the end of this lesson you can

  • Make a class abstract with ABC and @abstractmethod, and read the error when someone makes one directly
  • Say when Python checks that a child wrote every abstract method
  • Write an abstract getter, and a method in the parent that uses an abstract method
  • Use Sized and Iterable from collections.abc with isinstance

An item that's nothing in particular

Here's the family from lesson 4.9. LibraryItem is the parent, and each child says how long it can be borrowed for. The parent needs a loan_days() too, so that every item has one, and it returns 0 because a plain item has no loan period. Run it and look at the last line.

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

Someone needed a magazine, found no Magazine class, and made a plain LibraryItem on line 23. Nothing stopped them. It printed 0 days, so the magazine would be due back the day it was lent. Python didn't complain, and a quick look at the output might not either.

LibraryItem is only the idea that books, DVDs and magazines share: a title, a year, and some loan period. There's no such thing as an item that's none of them, so LibraryItem should never be made on its own. And its loan_days() on lines 6 and 7 isn't a real answer. It's there to say "every item has one of these", but it says it with a made-up number.

A class like this is abstract: it exists to be a parent, never to be made. Python can enforce that.

ABC and @abstractmethod

Line 1 imports two names from abc, Python's module for abstract base classes. Line 4 makes ABC the parent of LibraryItem. That on its own changes nothing you can see. It lets the class have abstract methods.

@abstractmethod, on line 9, is a decorator (lesson 3.4) that marks loan_days as abstract: a method the parent names but doesn't write. Every child must write its own. The body on line 11 is pass, which does nothing (lesson 4.1). The made-up return 0 is gone. In other code, and in Python's own documentation, you'll often see ... there instead: three dots, a value called Ellipsis. As a body it does the same as pass.

An abstract parent: its name and its abstract method are in italics
100%
«abstract» LibraryItem
  • +title: str
  • +year: int
  • +__init__(title: str, year: int)
  • +loan_days(): int
Book
  • +loan_days(): int
DVD
  • +loan_days(): int
  • Abstract 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.
Step 2 code main.py
Edit the code, then run it again

Book and DVD each write loan_days(), so they work as before. Line 26 shows a book is still a LibraryItem: an abstract class is a parent like any other.

So LibraryItem now says two things at once. What every item can do: tell you its loan period. And that it won't say how: that's each child's job. Code that loops over items, as on lines 24 and 25, only needs to know the "what". That's abstraction, the fourth idea of OOP from lesson 4.1.

Making one anyway

Here's the abstract LibraryItem again, and someone making one directly, as on line 23 of step 1. Press Run.

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

Python stops on line 14 with the last line:

TypeError: Can't instantiate abstract class LibraryItem without an implementation for abstract method 'loan_days'

To instantiate a class is to make an object from it. The message says LibraryItem is abstract, and names the method it has no code for. Line 15 never runs: the mistake is caught when the object is made, before anyone asks it for a loan period.

The same check catches a child that forgets one. This Magazine adds an issue, but nobody wrote its loan_days(). Press Run.

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

Making the magazine... prints, so Python was happy to read the class. Then line 21 stops with Can't instantiate abstract class Magazine without an implementation for abstract method 'loan_days'. Magazine got the abstract loan_days from its parent and never replaced it, so it's abstract too.

To fix it, add the method to Magazine, under __init__, and run it again:

    def loan_days(self):
        return 14

Notice when Python checks: when an object is made, not when the class is written and not before the program runs. A program that never makes a Magazine never hears about it. That's still much earlier than step 1, where the wrong loan period sailed through. If a class has several abstract methods missing, the message lists them all.

An abstract getter

Every item must also say what kind of thing it is, for the receipt. The parent can't know the answer, so it can't store it in __init__. Instead it names a getter, get_kind(), and makes it abstract on lines 9 to 11. Each child writes its own, and gives back its own answer.

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

Book answers "book" on line 16 and DVD answers "DVD" on line 21. Line 25 calls item.get_kind() without knowing which kind of item it has.

Rename DVD's method on line 20 to get_type and run it. DVD no longer has a get_kind of its own, and the TypeError names 'get_kind'. Python's check is about the name: a child must have something of its own called get_kind. It doesn't check what the method gives back, so a get_kind that returns a number would pass.

Parent methods that use abstract ones

An abstract class isn't only a list of rules. It can have ordinary methods too, and they can call the abstract ones. The parent writes the steps once, and each child fills in its own detail.

Step 5 code main.py
Edit the code, then run it again
  • due_date on lines 14 and 15 adds self.loan_days() days to the date the item was lent, with timedelta from lesson 2.7.
  • describe on lines 17 and 18 puts the loan period in a line of text.

Neither is written in Book or DVD. When line 34 calls item.due_date(lent) on the DVD, Python runs the parent's due_date, and the self.loan_days() inside it finds the DVD's own method: 7 days. That's the same lookup as in lesson 4.6, child first, then parent.

This is why the abstract method matters. due_date needs every item to have a loan_days(). The @abstractmethod makes sure each one does, before anyone can call due_date on it.

collections.abc: Sized and Iterable

Python has abstract classes of its own, in the module collections.abc. Two of them:

  • Sized: anything you can call len() on. It needs a __len__ method.
  • Iterable: anything a for loop can go through. It needs an __iter__ method.

This Shelf has both (lesson 4.11). On line 12, iter() hands back the list's own way of going through its items, so a loop over the shelf goes through the titles.

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

Lines 16 to 18 ask isinstance whether a shelf, some text and a number are Sized and Iterable. A shelf and text are both. A number is neither: len(1987) makes no sense.

Look at line 20, though. Shelf doesn't inherit from Sized: its family is only Shelf and object. Yet lines 16 and 19 say it's Sized anyway. These classes from collections.abc don't look at the family. They look at the methods. A class with a __len__ counts as Sized, whatever its parents.

That's how you can ask "can I call len() on this?" with isinstance(things, Sized), without listing every kind of thing that might have a length. Recognising a class by what it can do, not by its family, is the idea behind the next lesson, protocols.

In other languages

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

Abstract classes in three languages
PythonJavaRust
A class that can’t be made on its ownclass LibraryItem(ABC) with an abstract methodabstract class LibraryItemNo classes. A trait lists what a type must do, and is never a value itself
A method every child must write@abstractmethod on a methodabstract int loanDays();, with no bodyfn loan_days(&self) -> u32; in the trait, with no body
A method that uses itAn ordinary method in the abstract classAn ordinary method in the abstract classA default method in the trait
A missing method is foundWhen an object is made, as the program runsWhen compilingWhen compiling
What the children shareMethods and attributes, through inheritanceMethods and fields, through inheritanceOnly the trait’s methods: there’s no inheritance

The big difference is the timing. Java and Rust find a missing method when compiling, before the program can run at all. Python finds it when the object is made. C# works like Java here. Simple Rust 4.3 writes the loan_days rule as a trait.

Check what you learned

Three questions. Pick an answer, then check it.

What happens when this program runs?
from abc import ABC, abstractmethod


class Item(ABC):
    @abstractmethod
    def loan_days(self):
        ...

    def describe(self):
        return "an item"


class Map(Item):
    def describe(self):
        return "a map"


print("start")
print(Map().describe())
An abstract class has a method due_date that calls self.loan_days(), and loan_days is abstract. Calling dvd.due_date(lent) uses which loan_days?
A class has a __len__ method but no parents. What does isinstance(obj, Sized) give?

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