Function “如何成功”;捐赠一本书;作为类中的函数

Function “如何成功”;捐赠一本书;作为类中的函数,function,class,python-3.x,try-except,Function,Class,Python 3.x,Try Except,假设我有一个虚拟的电子图书馆,我在一个类下定义了一个函数,这个函数允许我通过一本书(它是一个对象)的ID号来检查一本书是否在给定的图书馆中,如果它不在,我将它附加到图书馆中。如果我在try-except块中测试它,即使我知道ID号不存在,我仍然会收到except消息。如果有人能帮我解决这个问题那就好了 class Library: # the class constructor def __init__(self, books, patrons): self.b

假设我有一个虚拟的电子图书馆,我在一个类下定义了一个函数,这个函数允许我通过一本书(它是一个对象)的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:
            donate_book(book)
            print("Thank you for your Donation!")
        except:
            print ("that id# is already taken, sorry")
我的库被定义为空列表 库=[] 我的try-Exception代码错误还是我的捐赠书代码错误

我的书本课:

 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)

我想您应该使用:

如果i.book\u id==book.book\u id:


在您的
捐赠图书()方法中。

重新定义您的
捐赠图书方法如下:

def donate_book(self, book):
    if book in self.books:
        raise DuplicateIdError()
    else:
        self.books.append(book)
手册
类中,定义此方法:

def __eq__(self, other):
    return self.book_id == other.book_id

这个覆盖了书与书之间的平等性测试。

谢谢,但是为什么如果我测试它,它总是打印“该id已经被占用了…”当我知道它不在库中时,你可以发布你的
类实现吗?你也可以发布你的主方法(你想要执行的代码)吗还有错误堆栈跟踪?我不明白的是我仍然没有得到应该得到的输出。我应该将图书馆定义为其他东西吗?
lib=library([],[])
然后,像这样调用方法:
lib.donate\u book(book('blotthouse V','Kurt Vonnegut',1234))
您的错误来自
donate\u book
方法中的
else
子句的错误位置。更改
donate\u book(book)
捐赠给
。捐赠图书(书)
。另一个好技巧是将
except:
更改为
except duplicateError:
,因为它现在正在捕获
namererror