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: 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]
- +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
- +item: LibraryItem
- +member: Member
- +due: date
- +days_late(today: date): int
- +fine(today: date): int
- +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)
- +author: str
- +__init__(title: str, year: int, author: str)
- +loan_days(): int
- +__str__(): str
- +minutes: int
- +__init__(title: str, year: int, minutes: int)
- +loan_days(): int
- +__str__(): str
- +issue: int
- +__init__(title: str, year: int, issue: int)
- +loan_days(): int
- +__str__(): str
- +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):
- 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:
| Idea | Where | Lesson |
|---|---|---|
| Abstraction | LibraryItem promises loan_days(), and can’t be made on its own | 4.13 |
| Inheritance | Book, DVD and Magazine get title, year and checking out from LibraryItem | 4.5, 4.6 |
| Polymorphism | Library.lend calls item.loan_days() and item.check_out() on any item | 4.9 |
| Encapsulation | Loans can only change through Member and Library; a Loan can’t change at all | 4.2 to 4.4 |
| An error family | LibraryError and its three children | 4.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).
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.
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.
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.
Memberkeeps its loans in_loans, and the only way to add one isadd_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). Loanis a frozen dataclass, so its due date can't be moved (lesson 4.4).
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:
findthe item, or raiseNotFound.- Check the member's limit, or raise
LimitReached. item.check_out(), which raisesNotAvailableif it's already lent.ReferenceBookoverridescheck_outto always raise it.- 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.
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.
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.
Some things to try:
- Add an
AudioBookwith a 28-day loan to desk.py, put one instock(), and lend it.Libraryneeds 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
finescommand that adds up what every overdue loan would cost if it came back today.
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.
- The Python Standard Library: abc
- The Python Tutorial: User-defined Exceptions
- dataclasses: Frozen instances
- Built-in Types: Tuples: a tuple can’t be changed
- The Python Standard Library: datetime.timedelta: adding days to a date
- OMG Unified Modeling Language (UML) 2.5.1: the standard the class diagrams follow