Velamuvi AIAcademy

Lesson 15 of 15 · Design

Project: Build a Small Class Library

Bring every Python OOP idea together in one project: build a small library system with classes, inheritance, an abstract class, properties, magic methods, composition and a custom exception.

  • 11 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • How to plan a program as a set of classes
  • How to use every idea from this course together in one project
  • How to create and use your own exception class
  • How the classes work together to run a small library

What you will build

In this project you will build the heart of a library management system: the code that keeps track of books, eBooks and members, and handles borrowing and returning. Every big idea from this course has a place in it.

The finished program will be able to:

  • load books from a simple text catalogue
  • lend items to members, with a different loan period for eBooks
  • stop a member from borrowing more than two items at once
  • refuse impossible actions with clear error messages
  • list everything that is available right now

Step 0: plan the classes

Good object-oriented programs start with a plan, not with code. List the things in the problem, then decide what each one is in charge of.

ClassIts responsibilityIdeas from this course
LibraryErrordescribe a broken library ruleinheritance from Exception
LibraryItemwhat every borrowable item has and must doabstract class, property, magic methods, encapsulation
Booka printed bookinheritance, super(), overriding
EBooka digital book with a shorter loaninheritance chain, extending __str__
Membera person and the items they haveclass attribute, property, encapsulation
Librarythe whole collection and the lending rulescomposition, class method, static method, magic methods

The relationships follow the rules you learned:

  • An eBook is a book, and a book is a library item, so they use inheritance.
  • A library has items and has members, so it uses composition.

Step 1: a custom exception

class LibraryError(Exception):
    """Raised when a library rule is broken."""

That is the whole class. It inherits everything it needs from Exception. The text in triple quotes is a docstring: a short description of the class. It also counts as the class's one line of body, so pass is not needed.

Now the library can write raise LibraryError("..."), and the code using it can write except LibraryError: to catch only library problems.

Step 2: the abstract item

Every item in the library has an id, a title and a loan status, and every item must say how long it can be borrowed for. That shared plan becomes an abstract class.

from abc import ABC, abstractmethod


class LibraryItem(ABC):
    def __init__(self, item_id, title):
        if not title.strip():
            raise ValueError("An item needs a title")
        self.item_id = item_id
        self.title = title
        self._on_loan = False

    @property
    def is_available(self):
        return not self._on_loan

    def check_out(self):
        self._on_loan = True

    def check_in(self):
        self._on_loan = False

    @abstractmethod
    def loan_days(self):
        pass

    def __str__(self):
        status = "available" if self.is_available else "on loan"
        return f"{self.title} ({status})"

    def __repr__(self):
        return f"{type(self).__name__}({self.item_id!r}, {self.title!r})"

    def __eq__(self, other):
        return self.item_id == other.item_id

Look at what each part does:

  • __init__ refuses an empty title, so a broken item can never exist.
  • _on_loan is protected. Outside code reads the status through the is_available property, and changes it only with check_out() and check_in().
  • loan_days() is abstract: every real kind of item must say its own loan period.
  • __str__, __repr__ and __eq__ are magic methods for printing and comparing. Two items are equal when they have the same id.

Step 3: books and eBooks

class Book(LibraryItem):
    def __init__(self, item_id, title, author):
        super().__init__(item_id, title)
        self.author = author

    def loan_days(self):
        return 14

    def __str__(self):
        return super().__str__() + f", by {self.author}"


class EBook(Book):
    def __init__(self, item_id, title, author, size_mb):
        super().__init__(item_id, title, author)
        self.size_mb = size_mb

    def loan_days(self):
        return 7

    def __str__(self):
        return super().__str__() + f", eBook {self.size_mb} MB"
  • Book inherits from LibraryItem. It calls super().__init__ for the shared set-up, then adds an author.
  • Book provides loan_days(), so it is a concrete class you can create.
  • EBook inherits from Book, overrides loan_days() with a shorter loan, and extends __str__ by adding to its parent's text.

Step 4: members

class Member:
    MAX_LOANS = 2

    def __init__(self, member_id, name):
        self.member_id = member_id
        self.name = name
        self._loans = []

    @property
    def can_borrow(self):
        return len(self._loans) < Member.MAX_LOANS

    def has(self, item):
        return item in self._loans

    def take(self, item):
        self._loans.append(item)

    def hand_back(self, item):
        self._loans.remove(item)

    def __str__(self):
        return f"{self.name} ({len(self._loans)} of {Member.MAX_LOANS} loans)"
  • MAX_LOANS is a class attribute: one rule shared by every member, written as a constant.
  • _loans is created in __init__, so each member gets their own list.
  • can_borrow is a computed property that is always up to date.

Step 5: the library

The Library class brings everything together. It has items and members, stored in dictionaries so they can be found quickly by id.

class Library:
    def __init__(self, name):
        self.name = name
        self._items = {}
        self._members = {}

    @classmethod
    def from_catalogue(cls, name, lines):
        library = cls(name)
        for line in lines:
            item_id, title, author = Library.split_line(line)
            library.add_item(Book(item_id, title, author))
        return library

    @staticmethod
    def split_line(line):
        parts = []
        for part in line.split("|"):
            parts.append(part.strip())
        return parts

    def add_item(self, item):
        self._items[item.item_id] = item

    def add_member(self, member):
        self._members[member.member_id] = member

    def _find(self, item_id, member_id):
        if item_id not in self._items:
            raise LibraryError(f"No item with id {item_id}")
        if member_id not in self._members:
            raise LibraryError(f"No member with id {member_id}")
        return self._items[item_id], self._members[member_id]

    def lend(self, item_id, member_id):
        item, member = self._find(item_id, member_id)
        if not item.is_available:
            raise LibraryError(f"{item.title} is already on loan")
        if not member.can_borrow:
            raise LibraryError(f"{member.name} has reached the limit of {Member.MAX_LOANS} loans")
        item.check_out()
        member.take(item)
        return f"{member.name} borrowed {item.title} for {item.loan_days()} days"

    def give_back(self, item_id, member_id):
        item, member = self._find(item_id, member_id)
        if not member.has(item):
            raise LibraryError(f"{member.name} does not have {item.title}")
        item.check_in()
        member.hand_back(item)
        return f"{member.name} returned {item.title}"

    def available(self):
        result = []
        for item in self._items.values():
            if item.is_available:
                result.append(item)
        return result

    def __len__(self):
        return len(self._items)

    def __contains__(self, item_id):
        return item_id in self._items
  • from_catalogue is a class method used as an alternative constructor: it builds a whole library from lines of text.
  • split_line is a static method: a helper that needs neither an object nor the class.
  • _find is a protected helper method, only meant for use inside the class.
  • lend and give_back delegate to the items and members, using their methods instead of reaching into their data. That is encapsulation and composition working together.
  • lend works with any kind of item. It just calls item.loan_days(), and books and eBooks answer differently. That is polymorphism.
  • __len__ and __contains__ let you write len(library) and "B1" in library.

Step 6: run the complete program

Here is every class together, followed by a short story that uses them. Run it, then try changing it.

Try it yourselfPython
from abc import ABC, abstractmethod


class LibraryError(Exception):
    """Raised when a library rule is broken."""


class LibraryItem(ABC):
    def __init__(self, item_id, title):
        if not title.strip():
            raise ValueError("An item needs a title")
        self.item_id = item_id
        self.title = title
        self._on_loan = False

    @property
    def is_available(self):
        return not self._on_loan

    def check_out(self):
        self._on_loan = True

    def check_in(self):
        self._on_loan = False

    @abstractmethod
    def loan_days(self):
        pass

    def __str__(self):
        status = "available" if self.is_available else "on loan"
        return f"{self.title} ({status})"

    def __repr__(self):
        return f"{type(self).__name__}({self.item_id!r}, {self.title!r})"

    def __eq__(self, other):
        return self.item_id == other.item_id


class Book(LibraryItem):
    def __init__(self, item_id, title, author):
        super().__init__(item_id, title)
        self.author = author

    def loan_days(self):
        return 14

    def __str__(self):
        return super().__str__() + f", by {self.author}"


class EBook(Book):
    def __init__(self, item_id, title, author, size_mb):
        super().__init__(item_id, title, author)
        self.size_mb = size_mb

    def loan_days(self):
        return 7

    def __str__(self):
        return super().__str__() + f", eBook {self.size_mb} MB"


class Member:
    MAX_LOANS = 2

    def __init__(self, member_id, name):
        self.member_id = member_id
        self.name = name
        self._loans = []

    @property
    def can_borrow(self):
        return len(self._loans) < Member.MAX_LOANS

    def has(self, item):
        return item in self._loans

    def take(self, item):
        self._loans.append(item)

    def hand_back(self, item):
        self._loans.remove(item)

    def __str__(self):
        return f"{self.name} ({len(self._loans)} of {Member.MAX_LOANS} loans)"


class Library:
    def __init__(self, name):
        self.name = name
        self._items = {}
        self._members = {}

    @classmethod
    def from_catalogue(cls, name, lines):
        library = cls(name)
        for line in lines:
            item_id, title, author = Library.split_line(line)
            library.add_item(Book(item_id, title, author))
        return library

    @staticmethod
    def split_line(line):
        parts = []
        for part in line.split("|"):
            parts.append(part.strip())
        return parts

    def add_item(self, item):
        self._items[item.item_id] = item

    def add_member(self, member):
        self._members[member.member_id] = member

    def _find(self, item_id, member_id):
        if item_id not in self._items:
            raise LibraryError(f"No item with id {item_id}")
        if member_id not in self._members:
            raise LibraryError(f"No member with id {member_id}")
        return self._items[item_id], self._members[member_id]

    def lend(self, item_id, member_id):
        item, member = self._find(item_id, member_id)
        if not item.is_available:
            raise LibraryError(f"{item.title} is already on loan")
        if not member.can_borrow:
            raise LibraryError(f"{member.name} has reached the limit of {Member.MAX_LOANS} loans")
        item.check_out()
        member.take(item)
        return f"{member.name} borrowed {item.title} for {item.loan_days()} days"

    def give_back(self, item_id, member_id):
        item, member = self._find(item_id, member_id)
        if not member.has(item):
            raise LibraryError(f"{member.name} does not have {item.title}")
        item.check_in()
        member.hand_back(item)
        return f"{member.name} returned {item.title}"

    def available(self):
        result = []
        for item in self._items.values():
            if item.is_available:
                result.append(item)
        return result

    def __len__(self):
        return len(self._items)

    def __contains__(self, item_id):
        return item_id in self._items


library = Library.from_catalogue("City Library", [
    "B1 | Clean Code | Robert Martin",
    "B2 | Dune | Frank Herbert",
    "B3 | Atomic Habits | James Clear",
])
ebook = EBook("E1", "Python Basics", "Ada Lovelace", 4.5)
library.add_item(ebook)

ada = Member("M1", "Ada")
library.add_member(ada)

print(library.name, "has", len(library), "items")
print(library.lend("B1", "M1"))
print(library.lend("E1", "M1"))
print(ada)

try:
    library.lend("B2", "M1")
except LibraryError as error:
    print("Refused:", error)

print(library.give_back("B1", "M1"))

print("Available now:")
for item in library.available():
    print(" -", item)

print("B9" in library)
print(repr(ebook))

Read the output line by line and match each one to the code that produced it. Notice the eBook's 7-day loan, the refusal when Ada reaches her limit, and how the returned book shows up as available again.

Common mistakes

Practice exercise

Add a search feature to a library, so readers can find books by any part of the title or author.

Your solutionPython
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author


class Library:
    def __init__(self):
        self._books = []

    def add(self, book):
        self._books.append(book)

    # Add a method search(self, text) that returns a list of the titles of every
    # book whose title OR author contains text, ignoring upper and lower case.


library = Library()
library.add(Book("Clean Code", "Robert Martin"))
library.add(Book("Dune", "Frank Herbert"))
library.add(Book("Python Crash Course", "Eric Matthes"))
print(library.search("python"))
print(library.search("HERBERT"))
print(library.search("cooking"))

# Output must be exactly:
# ['Python Crash Course']
# ['Dune']
# []
Knowledge check

In the project, why does Library call item.check_out() instead of setting item._on_loan = True itself?

Ideas to keep going

Practise by adding features of your own. Each one uses ideas from this course:

  • A Magazine class with a 3-day loan (inheritance and the abstract method).
  • A due_items() method on Member that lists everything they have (encapsulation).
  • A PremiumMember child class whose limit is 5 (a class attribute and overriding).
  • A search() method on Library, like the one in the exercise above.
  • A __repr__ for Member and Library, so they print helpfully while debugging.

Summary

  • Plan a program by listing its things and giving each class one responsibility.
  • Use inheritance for is-a relationships and composition for has-a relationships.
  • Abstract classes, properties, magic methods, class and static methods, encapsulation and custom exceptions all fit together in real programs.
  • Objects should ask other objects to do jobs, rather than reaching into their data.

You have finished Python Object-Oriented Programming

You can now design programs as classes and objects: write __init__, attributes and methods, use class methods, static methods and properties, make objects work with Python's operators through magic methods, build class families with inheritance and super(), choose between inheritance and composition, protect data with encapsulation, and set rules with abstract base classes. These are the ideas behind every major AI library you will use.

Where next?

Finished reading? Tick it off to track your progress.