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
- 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.
| Class | Its responsibility | Ideas from this course |
|---|---|---|
LibraryError | describe a broken library rule | inheritance from Exception |
LibraryItem | what every borrowable item has and must do | abstract class, property, magic methods, encapsulation |
Book | a printed book | inheritance, super(), overriding |
EBook | a digital book with a shorter loan | inheritance chain, extending __str__ |
Member | a person and the items they have | class attribute, property, encapsulation |
Library | the whole collection and the lending rules | composition, 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_idLook at what each part does:
__init__refuses an empty title, so a broken item can never exist._on_loanis protected. Outside code reads the status through theis_availableproperty, and changes it only withcheck_out()andcheck_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"Bookinherits fromLibraryItem. It callssuper().__init__for the shared set-up, then adds an author.Bookprovidesloan_days(), so it is a concrete class you can create.EBookinherits fromBook, overridesloan_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_LOANSis a class attribute: one rule shared by every member, written as a constant._loansis created in__init__, so each member gets their own list.can_borrowis 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._itemsfrom_catalogueis a class method used as an alternative constructor: it builds a whole library from lines of text.split_lineis a static method: a helper that needs neither an object nor the class._findis a protected helper method, only meant for use inside the class.lendandgive_backdelegate to the items and members, using their methods instead of reaching into their data. That is encapsulation and composition working together.lendworks with any kind of item. It just callsitem.loan_days(), and books and eBooks answer differently. That is polymorphism.__len__and__contains__let you writelen(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.
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
Add a search feature to a library, so readers can find books by any part of the title or author.
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']
# []
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
Magazineclass with a 3-day loan (inheritance and the abstract method). - A
due_items()method onMemberthat lists everything they have (encapsulation). - A
PremiumMemberchild class whose limit is 5 (a class attribute and overriding). - A
search()method onLibrary, like the one in the exercise above. - A
__repr__forMemberandLibrary, 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?
- Take the final quiz to check what you remember.
- Continue with Python Data Structures or Advanced Python.
- Follow a career roadmap to see what comes next for the job you want.
Finished reading? Tick it off to track your progress.