بتل کد Battle Codeدارد باز می‌شود…

جواب «Step 2: Borrow and Return» چالش 2 از جلسه‌ی 30

سؤال

گام ۲. مدل Book گام ۱ را نگه دارید و یک ویژگی borrower (پیش‌فرض None) اضافه کنید. کلاس استثنای LibraryError(Exception) و کلاس Library با متدهای add(book)، borrow(isbn, member) و give_back(isbn) بنویسید. خطاها (با پیام دقیق): کتاب ناموجود ← no such book، امانت کتاب امانت‌رفته ← already borrowed، بازگرداندن کتاب امانت‌نرفته ← not borrowed. دستورها تا end:
add <isbn>|<title>|<author> ← چاپ added: <title>
borrow <isbn> <member> ← چاپ <member> borrowed <title>
return <isbn> ← چاپ returned <title>
هر LibraryError را بگیرید و error: <پیام> چاپ کنید. (ورودی‌ها isbn معتبر دارند.)

راهنما

دستور را با split(maxsplit=1) جدا کنید. متدهای Library فقط استثنا بالا بیاورند یا عنوان برگردانند؛ چاپ با حلقه‌ی اصلی است.

یک جواب درست

from dataclasses import dataclass


class LibraryError(Exception):
    pass


@dataclass
class Book:
    isbn: str
    title: str
    author: str
    borrower: str | None = None

    def __post_init__(self):
        if len(self.isbn) != 13 or not self.isbn.isdigit():
            raise ValueError("invalid isbn")


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

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

    def _find(self, isbn):
        if isbn not in self.books:
            raise LibraryError("no such book")
        return self.books[isbn]

    def borrow(self, isbn, member):
        book = self._find(isbn)
        if book.borrower is not None:
            raise LibraryError("already borrowed")
        book.borrower = member
        return book.title

    def give_back(self, isbn):
        book = self._find(isbn)
        if book.borrower is None:
            raise LibraryError("not borrowed")
        book.borrower = None
        return book.title


lib = Library()
while True:
    line = input()
    if line == "end":
        break
    cmd, rest = line.split(maxsplit=1)
    try:
        if cmd == "add":
            book = Book(*rest.split("|"))
            lib.add(book)
            print(f"added: {book.title}")
        elif cmd == "borrow":
            isbn, member = rest.split()
            print(f"{member} borrowed {lib.borrow(isbn, member)}")
        elif cmd == "return":
            print(f"returned {lib.give_back(rest)}")
    except LibraryError as e:
        print(f"error: {e}")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن