Design a small library system with collaborating object classes.
What You Will Learn
Object-oriented design can model books, patrons, and loans as separate concepts. For a first version, track whether a book is checked out and reject duplicate checkouts; persistence, due dates, and simultaneous users are later extensions.
In a real system use immutable book IDs and database transactions for loans.
Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
class Book:
def __init__(self, title):
self.title = title
self.checked_out = False
def borrow(self):
if self.checked_out:
raise ValueError("Book is already borrowed")
self.checked_out = True
def return_book(self):
self.checked_out = False
book = Book("Python Fundamentals")
book.borrow()
print(book.checked_out)
book.return_book()
print(book.checked_out)
How the Example Works
- The class Book groups data and behavior; its methods run when called on an instance.
- The variable book holds the result of Book('Python Fundamentals'). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
True
False
When You Would Use This
A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.
Practice: Modify the Code
Add a Library class that stores several Book objects by identifier.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Trying to track checkout state only in presentation output without saving it on objects.
- Allowing the same book to be borrowed twice without checking existing state.
Key Takeaways
- Design a small library system with collaborating object classes.
- Object-oriented design can model books, patrons, and loans as separate concepts.
- In a real system use immutable book IDs and database transactions for loans.