Object-oriented programming · lesson 17 of 17
Parts in this lesson
Aclass LibraryItem(ABC)4.13: abstraction
Bclass DVD(LibraryItem)4.5: inheritance
Citem.loan_days()4.9: polymorphism
Dget_loans(), frozen=True4.3, 4.4: encapsulation
Eclass NotAvailable(LibraryError)4.8: an error family
Fdate + timedelta(days=…)2.7: due dates

Project: the loan desk

Last updated

Time to put Stage 4 together. You'll build the library's loan desk: books, DVDs, magazines and reference books that all come from one abstract class, members and loans that can't be put in a bad state, a library that lends and takes back any kind of item and refuses with its own errors, and tests that prove the rules hold. Every one of the four ideas of OOP has a job here.

By the end of this lesson you can

  • Plan a program as a set of classes, and say which OOP idea each part uses
  • Build a family of items on an abstract parent, each with its own loan period
  • Keep members and loans valid, and report broken rules with your own exceptions
  • Write one lending method that works for every kind of item, and test it

Plan it, with a class diagram

Here's a session at the finished loan desk. The input box gives it commands, and each answer comes from the classes you'll build.

Loan desk open on 2026-03-02. Commands: lend <name> <title>, return <name> <title>, loans <name>, wait <days>, overdue, quit
> lend sam dune
Sam has Dune by Frank Herbert (1965), due 2026-03-23.
> lend ana dune
Sorry: Dune is already on loan.
> lend sam rivers of ice
Sam has Rivers of Ice (2019, DVD, 52 min), due 2026-03-09.
> lend sam atlas of the world
Sorry: Atlas of the World is for reading in the library.
> lend sam garden monthly
Sam has Garden Monthly, issue 214, due 2026-03-16.
> lend sam emma
Sorry: Sam already has 3 items.
> wait 10
It is now 2026-03-12.
> overdue
Sam: Rivers of Ice, 3 days late
> return sam rivers of ice
Returned. Fine: 75 cents.
> loans sam
Dune by Frank Herbert (1965), due 2026-03-23
Garden Monthly, issue 214, due 2026-03-16
> return ana emma
Sorry: Ana hasn't borrowed Emma.
> lend zoe emma
Sorry: no member called zoe.
> quit

What it does: it keeps a stock of items and two members. lend and return take a member's name and a title. Each kind of item has its own loan period, and late returns cost 25 cents a day, up to 500 (lesson 1.P). wait moves the date on, and overdue lists late loans. Anything the library refuses comes back as a Sorry line.

The classes. Here's the class diagram of desk.py, the module you'll build. It's read as in lesson 4.1, step 2: an open triangle points from a child to its parent, a diamond marks a class that holds others, and every attribute and method shows its types.

Items, members and loans
100%
Library
  • #_items: dict[str, LibraryItem]
  • #_loans: list[Loan]
  • +__init__()
  • +add(item: LibraryItem)
  • +find(title: str): LibraryItem
  • +lend(title: str, member: Member, today: date): Loan
  • +give_back(title: str, member: Member, today: date): int
  • +overdue(today: date): Iterator[Loan]
«abstract» LibraryItem
  • +title: str
  • +year: int
  • #_on_loan: bool
  • +__init__(title: str, year: int)
  • +is_on_loan(): bool
  • +loan_days(): int
  • +check_out()
  • +check_in()
  • +__str__(): str
«dataclass, frozen» Loan
  • +item: LibraryItem
  • +member: Member
  • +due: date
  • +days_late(today: date): int
  • +fine(today: date): int
Member
  • +LIMIT: int
  • +name: str
  • #_loans: list[Loan]
  • +__init__(name: str)
  • +get_loans(): tuple[Loan, ...]
  • +check_can_borrow()
  • +add_loan(loan: Loan)
  • +loan_for(item: LibraryItem): Loan
  • +remove_loan(loan: Loan)
Book
  • +author: str
  • +__init__(title: str, year: int, author: str)
  • +loan_days(): int
  • +__str__(): str
DVD
  • +minutes: int
  • +__init__(title: str, year: int, minutes: int)
  • +loan_days(): int
  • +__str__(): str
Magazine
  • +issue: int
  • +__init__(title: str, year: int, issue: int)
  • +loan_days(): int
  • +__str__(): str
ReferenceBook
  • +check_out()
  • Abstract class LibraryItem; attributes: title, year, _on_loan; methods: __init__, is_on_loan, loan_days, check_out, check_in, __str__.
  • Class Book; inherits from LibraryItem; attributes: author; methods: __init__, loan_days, __str__.
  • Class ReferenceBook; inherits from Book; no attributes of its own; methods: check_out.
  • Class DVD; inherits from LibraryItem; attributes: minutes; methods: __init__, loan_days, __str__.
  • Class Magazine; inherits from LibraryItem; attributes: issue; methods: __init__, loan_days, __str__.
  • Dataclass Loan; attributes: item, member, due; methods: days_late, fine.
  • Class Member; attributes: LIMIT, name, _loans; methods: __init__, get_loans, check_can_borrow, add_loan, loan_for, remove_loan.
  • Class Library; attributes: _items, _loans; methods: __init__, add, find, lend, give_back, overdue.
  • Loan holds one LibraryItem in item.
  • Loan holds one Member in member.
  • Member holds many Loan in _loans.
  • Library holds many LibraryItem in _items.
  • Library holds many Loan in _loans.

The errors the library raises are a family of their own (lesson 4.8):

The library's errors
100%
LibraryError is an Exception
NotAvailable
LimitReached
NotFound
  • Class LibraryError; is a kind of Exception; no attributes of its own; no methods of its own.
  • Class NotAvailable; inherits from LibraryError; no attributes of its own; no methods of its own.
  • Class LimitReached; inherits from LibraryError; no attributes of its own; no methods of its own.
  • Class NotFound; inherits from LibraryError; no attributes of its own; no methods of its own.

Which idea does which job:

The four ideas in the loan desk
IdeaWhereLesson
AbstractionLibraryItem promises loan_days(), and can’t be made on its own4.13
InheritanceBook, DVD and Magazine get title, year and checking out from LibraryItem4.5, 4.6
PolymorphismLibrary.lend calls item.loan_days() and item.check_out() on any item4.9
EncapsulationLoans can only change through Member and Library; a Loan can’t change at all4.2 to 4.4
An error familyLibraryError and its three children4.8

Abstraction: LibraryItem

Start at the top of the tree. There's no such thing as a plain "library item" on the shelf. Every real one is a book, a DVD or a magazine. So LibraryItem is an abstract class (lesson 4.13): it says every item has a title, a year and a loan period, but leaves the loan period to each child.

__init__ also keeps the first rule: no item without a title (lesson 4.4).

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

Line 27 tries to make a plain LibraryItem, and Python refuses: loan_days has no implementation. Line 31 tries a book with no title, and __init__ refuses. Either way, a bad item never exists.

Inheritance: books, DVDs and magazines

Each kind of item is a child of LibraryItem (lesson 4.5). Each one calls super().__init__ for the title and year, adds what it has of its own, and gives its own loan_days.

To keep this step short, the parent here isn't abstract. It's the tree shape that matters.

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

Book overrides __str__ with its own (lesson 4.6). DVD extends its parent's version on line 31: super().__str__() gives Rivers of Ice (2019), and the DVD adds its running time. Magazine writes no __str__, so it uses its parent's. In the finished module, a magazine prints its issue number instead. Try writing that __str__ here.

Polymorphism: one loan loop for every item

The loan desk works out a due date the same way for every item: today plus the item's loan period. It never asks what kind of item it has.

Dates come from datetime (lesson 2.7). A timedelta is a length of time, and adding one to a date gives a new date. The examples fix "today" at 2 March 2026, so the output is the same every run.

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

The loop on line 30 is the whole point. Add a fourth class, say AudioBook with a 28-day loan, put one in the basket, and the loop works without a single change. That's polymorphism (lesson 4.9).

Encapsulation: members and loans that stay valid

Two rules must always hold: a member never has more than their limit, and a loan, once made, never changes.

  • Member keeps its loans in _loans, and the only way to add one is add_loan, which checks the limit first (lesson 4.4).
  • The getter get_loans() hands out a tuple, a copy that can't be changed (lessons 4.3 and 4.4).
  • Loan is a frozen dataclass, so its due date can't be moved (lesson 4.4).
Step 5 code main.py
Edit the code, then run it again

The last two attempts both fail. Line 40 tries to append to the tuple, and line 44 tries to move a due date. Neither can get round the rules. (The underscore in _loans can still be ignored, as lesson 4.2 showed. That's Python's trust, and it's why the tidy way in has to exist.)

A library that lends, with its own errors

Now everything goes into one module, desk.py, with the last class, Library, and an error family (lesson 4.8): LibraryError, with NotAvailable, LimitReached and NotFound under it. Open the desk.py tab and read Library.lend. It does four things, in an order that matters:

  1. find the item, or raise NotFound.
  2. Check the member's limit, or raise LimitReached.
  3. item.check_out(), which raises NotAvailable if it's already lent. ReferenceBook overrides check_out to always raise it.
  4. Only then make the Loan, and record it on the member and in the library.

All the checks come before any change, so a refused loan leaves everything as it was. Loan names its member with the text "Member" on line 97 of desk.py, because the Member class is written further down. A type hint in quotes is allowed to refer ahead.

Step 6 code
Edit the code, then run it again

Line 18 catches LibraryError, the parent, so all three refusals are caught by one except, and type(e).__name__ shows which child it was. A ReferenceBook can't be lent, but it doesn't break anything. It refuses with the same error the parent's check_out can raise, so it still works wherever a LibraryItem does (lesson 4.9).

Line 20 returns Dune 4 days late: 100 cents.

Tests

The rules are only worth something if they hold, so test them. Each test builds a small library, does one thing, and checks the result, in the pytest style of lesson 2.10.

Step 7 code
Edit the code, then run it again

test_limit_leaves_item_on_shelf is the important one: after a refused loan, the DVD must not be marked as lent. Break it on purpose: in desk.py, move item.check_out() above member.check_can_borrow() in Library.lend, and run the tests. The failure shows why the order in step 6 matters.

On your own computer, save the tests as test_desk.py without the last four lines, beside desk.py, and run them with pytest in a virtual environment (lesson 2.9):

python -m venv .venv
.venv\Scripts\activate        # on macOS or Linux: source .venv/bin/activate
pip install pytest
pytest

The finished loan desk

Here's the whole program. main.py reads commands, and the desk.py tab has the classes. who_and_what splits sam the hobbit into a member and a title, and raises NotFound for a name it doesn't know. The loop catches LibraryError once, for every command, so every refusal from anywhere in the module comes out as one Sorry line.

Step 8 code
Edit the code, then run it again

Some things to try:

  • Add an AudioBook with a 28-day loan to desk.py, put one in stock(), and lend it. Library needs no change.
  • Give staff members a higher limit with a subclass of Member, or better, with a policy object as in lesson 4.15.
  • Add a fines command that adds up what every overdue loan would cost if it came back today.
Why does Library.lend check the member's limit before calling item.check_out()?
Which OOP idea lets Library.lend work unchanged when you add an AudioBook class?

That's Stage 4 done, and with it, object-oriented programming in Python. In the capstone you'll move to your own computer and build the full library management system around this loan desk, with a catalogue, saving, reports and a menu.

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