この仮想電子図書館があり、クラスの下に定義された関数があり、本が特定の図書館にあるかどうかを ID NUMBER OF THE BOOK (オブジェクト) で確認し、そうでない場合は、ライブラリに追加します。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)