编写一个函数来重新设置图书馆试图重新出版由指定赞助人当前持有的图书。这本书从赞助人的借阅转移到图书馆的可用书籍清单。 我编写了大部分内容,但我不确定我的循环是否正确,我不知道在哪里插入我的missingIdError,有什么建议吗?注意:我还有一个Patron Class,并且已经将它们与ID一起定义,因此无需担心缺少的课程。
class DuplicateIdError (Exception):
def __init__(self, id, category = "Book" or "Patron"):
self.id = int(id)
self.category = str(category)
def __str__(self):
return 'duplicate {} ID: #{}'.format(self.category,self.id)
def __repr__(self):
return 'duplicate {} ID: #{}'.format(self.category,self.id)
class MissingIdError (LookupError):
def __init__(self, id, category = "Book" or "Patron"):
self.id = int(id)
self.category = str(category)
def __str__(self):
return 'duplicate {}: {}'.format(self.id, self.category)
def __repr__(self):
return 'duplicate {}: {}'.format(self.id, self.category)
class Library:
def __init__(self, books=None, patrons=None):
self.books = []
self.patrons = []
def __str__(self):
return "Library(<{}>, <{}>)".format(self.self.books, self.patrons)
def __repr__(self):
return "Library(<{}>, <{}>)".format(self.self.books, self.patrons)
#Returns None.
#Raises a DuplicateIdError if there's already a book in the library with that id#.
#Raises a MissingIdError if the patron or book wasn't found
def reshelve_book(self, patron_id, book_id):
for patron in self.patrons:
for book in self.books:
try:
if book.book_id == book_id:
raise DuplicateIdError(book_id,"Book")
elif book.book_id != book_id:
self.books.append(book)
book.borroweds.remove(book)
答案 0 :(得分:1)
只有几个简单的警卫会给你另一个例外:
def reshelve_book(self, patron_id, book_id):
if patron_id not in self.patrons:
raise MissingIdError(patrod_id, 'Patron')
我不理解book.borroweds.remove(book)
,但可能需要测试book_id
已被借用。
你真的需要一个循环吗?
def reshelve_book(self, patron_id, book_id):
if patron_id not in self.patrons:
raise MissingIdError(patrod_id, 'Patron')
if book_id in self.books:
raise DuplicateIdError(book_id,"Book")
try:
book = self.patrons[patron_id].borrowed_books[book_id]
except KeyError:
raise MissingIdError(book_id, 'Book')
self.books[book_id] = book
del self.patrons[patron_id].borrowed_books[book_id]
BTW:您的例外构建者不会做我认为您认为的事情:
def __init__(self, id, category = "Book" or "Patron"):
等同于:
def __init__(self, id, category = True):
我会避免为category
设置默认的arg:
def __init__(self, id, category):