Classes and objects · lesson 3 of 7
Parts in this lesson
Aself.book = bookan object holding an object
Bloan.book.titledot after dot
Cself.loans = []a list of objects
Dbook.lend()asking another object
Ereturn book1.8: give an object back

Objects working together

Last updated

A library isn't one book. It's books, members and loans, all tied together. In this lesson you'll give a loan a book and a member as attributes, give each member a list of books, write methods that ask other objects to do their part, pass objects to functions and get them back, and read the error you get when a class is stored where an object should be.

By the end of this lesson you can

  • Give an object attributes that hold other objects, and reach through them with dots
  • Keep a list of objects inside another object
  • Write methods that call other objects' methods, so each object looks after its own data
  • Pass objects to functions and return them, knowing both sides share one object

An object as an attribute

A loan is a book lent to a member for some days. So a Loan object holds a Book object and a Member object.

An attribute can hold any object, including one made from your own class. self.book = book stores the book that was passed in.

To reach inside, use dot after dot: loan.book is the book, and loan.book.title is its title.

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

Lesson 3.1 said a name is a label on an object. An attribute is a label too. loan.book and dune are two labels on one book, which is what line 23 checks. So when line 24 renames the book, the loan sees the new title. Watch it run, and see loan and dune change together.

That's what you want here: there's one copy of Dune in the building, and the loan points at it.

A list of objects

A member can have many loans, so a Member keeps a list of books. __init__ gives every new member their own empty list, self.loans = [].

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

sam.loans is a list, so sam.loans.append(...) works like any list. Each item in it is a Book, so line 18 can read book.title from each one.

Ana's list is empty: she has her own list, separate from Sam's, because __init__ made a new one for each member.

Methods that call other objects' methods

When Sam borrows Dune, two things must happen. The book loses a copy from the shelf, and Sam's list gains the book.

Each object should look after its own data. So Member.borrow doesn't change book.copies itself. It asks the book to do it, with book.lend(), and then adds the book to the member's own list. If there's no copy left, lend raises a ValueError (lesson 2.6). It's raised before the book is added to the list, so a failed loan changes nothing.

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

Watch it run and follow line 32. It jumps into Member.borrow, then into Book.lend, and back out.

The rule "no lending with zero copies" lives in Book, the class that owns copies. Any code that lends a book goes through it. Stage 4 calls this idea encapsulation.

Objects as arguments and return values

Objects can be passed to functions and given back, like any value. find takes a list of books and some words, and it returns the first book whose title contains them, or None if none do.

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

The book find gives back isn't a copy. It's the same object that's in catalogue. So when line 23 changes its author, catalogue[1] shows the change.

Change line 20 to look for "zzz". find gives back None, and line 21 stops with an AttributeError, because None has no title. Code that calls find must check for None first: if book is None:.

The class instead of an object

Line 13 should lend Dune, but something's off. Run it.

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

type object 'Book' has no attribute 'title'. Line 13 passed Book, the class, where it meant dune, a book made from the class. Python accepted it: it has no way to know what Loan expects. The mistake only shows up on line 14, when something reads loan.book.title. A class has no title. Each book gets its own in __init__.

Change Book to dune on line 13 and run it again. When you see type object in an error, look for a class name with no brackets after it.

In other languages

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

Objects that hold objects
PythonJavaRust
An object in an attributeThe attribute is a label on the other object. Both can be reached and changedThe field holds a reference, as in PythonThe struct owns the value inside it. Sharing it takes a borrow or a smart pointer
Asking another object to actbook.lend()book.lend()book.lend(), on a &mut Book
Passing an object to a functionThe function gets a label on the same objectThe method gets a reference to the same objectThe value moves in, or is lent with & or &mut
A class where an object should beAllowed. Fails when an attribute is readWon’t compileWon’t compile

Building an object out of other objects is called composition. Rust leans on it in place of inheritance: see Simple Rust 4.1. Python can do both, and lesson 4.15 compares them.

Check what you learned

Three questions. Pick or type an answer, then check it.

What does this program print?
class Member:
    def __init__(self, name):
        self.name = name
        self.loans = []


sam = Member("Sam")
mine = sam.loans
mine.append("Dune")
print(len(sam.loans))
Why does Member.borrow call book.lend() instead of writing book.copies -= 1 itself?
AttributeError: type object 'Book' has no attribute 'title'. What's the likely mistake?

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