Python 3D Academyবাংলা

Project: a library system

🌍 In real life. A school library lends books. A paper book can be with only one student at a time: once it's borrowed, the next student has to wait. An e-book is different: any number of students can read it at once. The librarian wants to add books, lend them, take them back, and print a list showing what's on the shelf.

In this project you'll build that system with everything from World 4: an Enum, a dataclass, inheritance with an overridden method, and a class that protects its rules.

The plan in one sentence: a Status Enum names the two states, a Book dataclass holds each book, an EBook child changes how lending works, and a Library class keeps the books and enforces the rules.

Its words:

  • state: whether a book is AVAILABLE or BORROWED
  • rule: a borrowed paper book can't be borrowed again; the Library refuses with a ValueError
  • override: EBook writes its own can_borrow and lend, so the same calls behave differently

Step by step, the plan:

  1. Status(Enum): the only two states a book can be in.
  2. @dataclass Book: title, author, status, plus can_borrow, lend and give_back.
  3. class EBook(Book): always borrowable, and lending changes nothing.
  4. class Library: a dictionary of books by title, with add, borrow, give_back and report.

When the library asks a book can_borrow(), Python climbs the lookup tower. An e-book answers from its own class:

Steps 1 and 2: the data. A book's state is one of a fixed set of choices, so it's an Enum: Status.BORROWED can't be misspelt the way "borowed" could. The book is mostly data, so @dataclass writes __init__ and __repr__, and the default status = Status.AVAILABLE means a new book starts on the shelf.

Step 3: the e-book. An e-book is a book, so it inherits. It overrides two methods: can_borrow always says True, and lend does nothing, because there's no copy to take off the shelf.

Step 4: the rules. The Library is the only place that lends, so it's the place to check: a missing title or a book that can't be borrowed raises a ValueError with a clear message, and nothing changes.

from dataclasses import dataclass
from enum import Enum


class Status(Enum):
    AVAILABLE = 1
    BORROWED = 2


@dataclass
class Book:
    title: str
    author: str
    status: Status = Status.AVAILABLE

    def can_borrow(self):
        return self.status == Status.AVAILABLE

    def lend(self):
        self.status = Status.BORROWED

    def give_back(self):
        self.status = Status.AVAILABLE


class EBook(Book):
    """An e-book has unlimited copies, so it can always be borrowed."""

    def can_borrow(self):
        return True

    def lend(self):
        pass


class Library:
    def __init__(self):
        self.books = {}

    def add(self, book):
        self.books[book.title] = book

    def borrow(self, title):
        if title not in self.books:
            raise ValueError(f"No book called {title}")
        book = self.books[title]
        if not book.can_borrow():
            raise ValueError(f"{title} is already borrowed")
        book.lend()

    def give_back(self, title):
        self.books[title].give_back()

    def report(self):
        lines = []
        for title in sorted(self.books):
            book = self.books[title]
            state = "available" if book.can_borrow() else "borrowed"
            lines.append(f"{title} by {book.author}: {state}")
        return lines


library = Library()
library.add(Book("Dune", "Herbert"))
library.add(EBook("Gitanjali", "Tagore"))
library.borrow("Dune")
library.borrow("Gitanjali")
try:
    library.borrow("Dune")
except ValueError as e:
    print("Refused:", e)
for line in library.report():
    print(line)
Dune is lent and then refused, while Gitanjali, an e-book, stays available after being borrowed.

Why build it this way, and what it costs. Each class has one job, and the Library never asks "is this an e-book?": it just calls can_borrow() and lend(), and each kind of book answers for itself (polymorphism, Lesson 22.3). Adding an audiobook later means one new child class, with no change to Library. Lending and returning look a book up by title in a dictionary, which takes about the same time for 10 books or 10,000; only report() walks and sorts them all.

Mistakes and edge cases.

  • Checking the type in Library. if isinstance(book, EBook): inside borrow works, but every new kind of book would need another if.
  • Changing status from outside. library.books["Dune"].status = Status.AVAILABLE skips the rules; go through give_back.
  • Comparing with a string. book.status == "AVAILABLE" is always False: compare with Status.AVAILABLE.
  • A missing title. self.books[title] on an unknown title raises a KeyError; check in first and raise a clear ValueError instead.

Quiz

  1. What does this print?

    from dataclasses import dataclass
    from enum import Enum
    
    
    class Status(Enum):
        AVAILABLE = 1
        BORROWED = 2
    
    
    @dataclass
    class Book:
        title: str
        author: str
        status: Status = Status.AVAILABLE
    
        def can_borrow(self):
            return self.status == Status.AVAILABLE
    
        def lend(self):
            self.status = Status.BORROWED
    
        def give_back(self):
            self.status = Status.AVAILABLE
    
    b = Book("Dune", "Herbert")
    b.lend()
    print(b.status.name, b.can_borrow())
  2. Why is EBook a child class of Book instead of a separate class?

    • An e-book is a book, and only its lending rules differ
    • Because dataclasses can't be used twice
    • So that it can't be borrowed
  3. This should say the book is available, but it prints False. Which line has the mistake?

    from enum import Enum
    class Status(Enum):
        AVAILABLE = 1
    status = Status.AVAILABLE
    print(status == "AVAILABLE")
  4. What does this print?

    from dataclasses import dataclass
    from enum import Enum
    
    
    class Status(Enum):
        AVAILABLE = 1
        BORROWED = 2
    
    
    @dataclass
    class Book:
        title: str
        author: str
        status: Status = Status.AVAILABLE
    
        def can_borrow(self):
            return self.status == Status.AVAILABLE
    
        def lend(self):
            self.status = Status.BORROWED
    
        def give_back(self):
            self.status = Status.AVAILABLE
    
    
    class EBook(Book):
        """An e-book has unlimited copies, so it can always be borrowed."""
    
        def can_borrow(self):
            return True
    
        def lend(self):
            pass
    
    
    class Library:
        def __init__(self):
            self.books = {}
    
        def add(self, book):
            self.books[book.title] = book
    
        def borrow(self, title):
            if title not in self.books:
                raise ValueError(f"No book called {title}")
            book = self.books[title]
            if not book.can_borrow():
                raise ValueError(f"{title} is already borrowed")
            book.lend()
    
        def give_back(self, title):
            self.books[title].give_back()
    
    lib = Library()
    lib.add(Book("Dune", "Herbert"))
    lib.borrow("Dune")
    try:
        lib.borrow("Dune")
    except ValueError as e:
        print(e)
  5. Where should the rule "a borrowed paper book can't be borrowed again" be checked?

    • In Library.borrow, the one place that lends
    • In every place that prints a book
    • Nowhere: students will remember

Coding tasks

  1. Step 1: books and their state. Write Status, an Enum with AVAILABLE = 1 and BORROWED = 2, and Book, a dataclass with title, author and status (default Status.AVAILABLE). Give Book three methods: can_borrow() (True when available), lend() (sets BORROWED) and give_back() (sets AVAILABLE).

  2. Step 2: e-books and the library. Add EBook(Book), whose can_borrow() always returns True and whose lend() does nothing. Then add Library, with a books dictionary (title → book) and three methods:

    • add(book)
    • borrow(title): raise ValueError if there's no such title or the book can't be borrowed; otherwise call book.lend()
    • give_back(title)
  3. Step 3: the shelf report. Add report() to Library. It returns a list of lines, one per book, sorted by title, like Dune by Herbert: borrowed or Gitanjali by Tagore: available. An e-book is always available.