假设我有这个虚拟电子图书馆,并且我在一个类下定义了一个函数,该函数允许我通过书的 ID 编号(这是一个对象)检查一本书是否在给定的图书馆中,如果不是,我将它附加到库中。如果我在 try-except 块中对其进行测试,即使我知道 ID 号尚不存在,我也会不断收到 except 消息。如果有人可以帮助我解决这个问题,那就太好了。
class Library:
# the class constructor
def __init__(self, books, patrons):
self.books=books
self.patrons=patrons
def __str__(self):
s="Patron("
for patron in self.patrons:
s+=str(patron) + ', '
if len(self.patron) != 0:
s= s[:-2]
s+=']'
for book in self.books:
s+=str(book) + ', '
if len(self.books) != 0:
s= s[:-2]
s+='])'
return s
def __repr__(self):
return str(self)
def donate_book(self, book):
for i in self.books:
if i==book.book_id:
raise DuplicateIdError()
else:
Library.append(book)
这是我的 try-except 块:
try:
donate_book(book)
print("Thank you for your Donation!")
except:
print ("that id# is already taken, sorry")
我的库被定义为一个空列表 library=[] 是我的 try-except 块代码错误还是我的 donate_book 代码错误?
我的书课:
class Book:
# the class constructor
def __init__(self, author, title, book_id):
self.title = title
self.author = author
self.book_id = book_id
def __str__(self):
s = "Books("+self.author+", "+self.title+", "+self.book_id+")"
return s
def __repr__(self):
return str(self)
我将重复错误定义为:
class DuplicateIdError(Exception):
#the class constructor
def __init__(self, ident):
self.ident= ident
def __str__(self):
s= print("'duplicate identificatoin: #" + self.ident + ".'")
return s
# returns a string rep matching
def __repr__(self):
return str(self)