Classes and objects · lesson 7 of 7
Parts in this lesson
A@dataclass(order=True)3.6: a Book
BBook.from_csv_row3.4: from a CSV row
Cself.loans.append(book)3.3: objects holding objects
D", ".join(titles)joins text with a separator
Easdict(book), Book(**data)an object to a dict and back
Fimport cards2.7 and 2.10: a module, tested

Project: book cards

Last updated

Time to put Stage 3 together. The 2.P catalogue kept each book as a dict. You'll replace those dicts with objects: a Book dataclass that prints as a tidy card, loads from the CSV file and sorts, a Member who borrows and gives back real Book objects, JSON saving that turns objects into data and back, tests, and a finished program that ties it all together.

By the end of this lesson you can

  • Plan a program around classes: what each one holds and what it can do
  • Build a dataclass that loads from a CSV row, prints as a card and sorts
  • Have one object keep and change a list of other objects, with rules that raise errors
  • Save objects to JSON and load them back, and test the classes

Plan it

In 2.P a book was a dict, and every function had to trust that the dict had the right keys. Now each book will be an object, made from a class that says what a book holds and what it can do. Here's a session with the finished program:

5 books. Commands: list, authors, find <words>, borrow <title>, return <title>, loans, quit
> list
Beloved      Toni Morrison      1987  1 on the shelf
Dune         Frank Herbert      1965  2 on the shelf
Emma         Jane Austen        1815  1 on the shelf
Matilda      Roald Dahl         1988  3 on the shelf
The Hobbit   J. R. R. Tolkien   1937  2 on the shelf
> borrow dune
Sam borrowed Dune.
> borrow emma
Sam borrowed Emma.
> borrow emma
Sorry: no copies of Emma left.
> borrow a
Sorry: 'a' matches 3 books, not 1.
> loans
Sam's loans: Dune, Emma
> return dune
Sam gave back Dune.
> find dahl
Matilda      Roald Dahl         1988  3 on the shelf
> quit
Saved 5 books to catalogue.json.

The classes. A good first guess: the nouns in the plan become classes, and the verbs become methods.

  • Book holds a title, an author, a year and a number of copies. It can be made from a CSV row, print itself as a card, sort by title, and lend or take back a copy.
  • Member holds a name, a limit on loans, and a list of the Book objects they've borrowed. They can borrow a book and give one back.

The pieces, and the lesson each comes from:

  1. Book is a dataclass with order=True (3.6). Copies don't count when comparing (3.6), and __str__ makes the card (3.5).
  2. Book.from_csv_row is a class method (3.4).
  3. Member holds a list of books and asks each book to lend itself (3.3).
  4. The catalogue is saved to JSON (2.8), with each book turned into a dict first.
  5. Everything moves into a module, cards.py, with tests (2.7 and 2.10).

Book as a dataclass

Start with the book. The fields are in the order to sort by, title first. copies gets a default of 1 and compare=False: two cards for Dune are the same book, however many copies are on the shelf.

__str__ makes the card. {self.title:<12} in an f-string pads the title with spaces to 12 characters, so the columns line up, as in 2.P.

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

Line 19 shows __repr__ is still the one @dataclass wrote: writing __str__ only changes what print shows. Line 20 is True though the copies differ.

Book.from_csv_row

Books come from the same books.csv as in 2.P. Every value in a CSV file is text, so from_csv_row turns the year and the copies into numbers as the book is made. Once a Book exists, the rest of the program can trust it.

load_books is one comprehension: a Book for every row.

Step 3 code
Edit the code, then run it again

Compare it with 2.P's load_books. That one changed the row dict in place, key by key. This one makes objects, and the class decides what a book is.

Add a sixth book to the books.csv tab and run it again.

Member with a list of books

A member keeps a list of the Book objects they've borrowed. field(default_factory=list) gives each member their own list (3.6).

borrow checks the member's own rule first: no more than limit books. Then it asks the book to lend itself, so the book checks its rule: no lending with no copies. Each class guards its own data. If either check fails, a ValueError is raised before anything changes.

", ".join(titles) on line 52 joins a list of text into one piece of text, with ", " between each pair. It's the opposite of splitting.

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

try_to takes a method and a book, and calls one with the other inside try. ana.borrow without brackets is a method used as a value, like the functions passed around in lesson 2.5. It remembers its object, so action(book) on line 41 runs ana.borrow(book).

Watch it run. When Sam gives back Emma on line 57 and Ana borrows it on line 58, the same Book object leaves Sam's list and joins hers.

Sort the catalogue

Because of order=True, sorted(books) sorts by title, the first field. For any other order, give sorted a key (lesson 2.5). by_author sorts by author, then title.

Step 5 code
Edit the code, then run it again

Look closely at By author: Frank, J. R. R., Jane, Roald, Toni. It sorted by first name, because author is one piece of text and that's where it starts. Libraries sort by surname. Try this key in by_author: (b.author.split()[-1], b.title). .split() cuts text into a list of words, and [-1] is the last one.

min and max take a key too: line 36 finds the oldest book by its year.

Save to JSON and load it back

Lesson 2.8 saved lists and dicts as JSON. JSON doesn't know what a Book is, so each book has to become a dict first, and become a book again when it's loaded.

  • asdict(book), from dataclasses, turns a dataclass object into a dict of its fields. save_books dumps a list of them.
  • Book(**data) goes the other way. ** passes each key in the dict as a keyword argument, the **kwargs from lesson 2.5 in reverse. So Book(**{"title": "Dune", ...}) is Book(title="Dune", ...).

Both functions are in the cards.py tab, which this program imports.

Step 6 code
Edit the code, then run it again

Line 8 shows the dict for Dune, with its copies down to 1 after Sam's loan. Lines 10 and 11 save every book and load them all back as new Book objects. Line 13 checks the round trip: the books are equal, and the copies survived too. Equality ignores copies, so line 13 checks those on their own. Open catalogue.json under the output to see the file.

Why save JSON and not CSV? JSON keeps numbers as numbers, and later in the course a member's loans, a list inside a member, go in the same file. CSV can't hold a list inside a row.

A module, and tests

Everything now lives in cards.py: the two classes, and the functions load_books, save_books, load_saved, find and by_author. Open its tab to read it all together.

Classes are easy to test: make objects, call methods, and check the attributes. These tests are in the pytest style from lesson 2.10. The page has no pytest, so the last lines call them by hand.

Step 7 code
Edit the code, then run it again

Break something on purpose. In cards.py, take compare=False off copies and run the tests again. test_equal_books_ignore_copies fails.

On your own computer (lesson 2.9), put cards.py and the tests in a project folder, saved as test_cards.py without the last four lines. Then make a virtual environment, install pytest into it with pip, and let pytest find and run the tests:

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

The finished program

Here's the whole program. main.py handles the commands, and the cards.py tab has the classes. pick turns the words after borrow or return into exactly one book, or raises a ValueError saying how many matched. The whole command loop catches ValueError in one place, so every rule broken anywhere, in pick, Member or Book, comes out as one tidy Sorry line. When the user types quit, the catalogue is saved to JSON.

Step 8 code
Edit the code, then run it again

Run it, then Watch it run and follow borrow emma the second time, from pick down to Book.lend.

Some things to try:

  • Add a card command that prints one book with print(pick(books, rest)).
  • Start from the saved file when there is one: load catalogue.json with load_saved if it exists, and books.csv only the first time. os.path.exists("catalogue.json") tells you which. (In the page each run starts in an empty folder, so try this on your own computer.)
  • Add a second member, and a who <name> command to switch between them.
What does this program print?
titles = ["Dune", "Emma"]
print(" / ".join(titles))
Why does Member.borrow call book.lend() before self.loans.append(book)?

That's Stage 3 done: you can write classes, make objects work together, and make them print, compare, sort and save. But Python still lets anyone write dune.copies = -5, and there's only one kind of item. Stage 4 fixes both, with the four ideas of object-oriented programming.

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