Skip to content

Exercises: full OOP design

These exercises combine everything covered in the OOP chapter — classes, inheritance, encapsulation, properties, magic methods, and ABCs. No scaffolding, no hints — just the requirements and the expected output.


Exercise 9 — Library management system Advanced

Section titled “Exercise 9 — Library management system Advanced”

Design a Library Management System with the following classes:

  • Book — title, author, ISBN, available (bool)
  • Member — name, member ID, list of borrowed books (max 3)
  • Library — collection of books and members, with:
    • add_book(book) / remove_book(isbn)
    • register_member(member) / remove_member(member_id)
    • borrow_book(member_id, isbn) — with proper error handling
    • return_book(member_id, isbn)
    • search_by_author(author) — returns list of matching books
    • available_books() — returns all books not currently borrowed
    • __str__ showing library stats
Expected output
lib = Library("City Library")
lib.add_book(Book("1984", "Orwell", "ISBN001"))
lib.add_book(Book("Dune", "Herbert", "ISBN002"))
lib.register_member(Member("Alice", "M001"))
lib.borrow_book("M001", "ISBN001")
print(lib.available_books()) # [Dune by Herbert]
lib.return_book("M001", "ISBN001")
print(lib.available_books()) # [1984 by Orwell, Dune by Herbert]
print(lib) # City Library — 2 books, 1 members
Solution

Exercise 10 — Challenge: Matrix Advanced

Section titled “Exercise 10 — Challenge: Matrix Advanced”

Implement a Matrix class that behaves like a mathematical matrix:

  • __init__ takes a 2D list
  • __add__, __sub__, __mul__ (matrix × matrix AND matrix × scalar)
  • __eq__, __repr__
  • __getitem__ so m[row][col] works
  • transpose() returning a new Matrix
  • determinant() for 2×2 and 3×3 matrices
  • is_square(), rows, cols as properties
  • Raise ValueError for incompatible dimensions
Expected output
m1 = Matrix([[1, 2], [3, 4]])
m2 = Matrix([[5, 6], [7, 8]])
print(m1 + m2) # Matrix([[6, 8], [10, 12]])
print(m1 * m2) # Matrix([[19, 22], [43, 50]])
print(m1 * 2) # Matrix([[2, 4], [6, 8]])
print(m1.transpose()) # Matrix([[1, 3], [2, 4]])
print(m1.determinant()) # -2.0
print(m1[0][1]) # 2
print(m1.rows) # 2
print(m1.cols) # 2
print(m1.is_square()) # True
Solution