How to successfully "donate a book" as a function within a class

89 views Asked by At

Let's say I have this virtual E-library and I have a function defined under a class that allows me to check if a book is in a given library BY ID NUMBER OF THE BOOK (which is an object) and if it isn't, I append it to the library. If I test it in a try-except block I keep getting the except message even though I know the ID number doesn't already exist. If someone can help me figure out this problem that would be good.

 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)

This is my try-except block:

        try:
            donate_book(book)
            print("Thank you for your Donation!")
        except:
            print ("that id# is already taken, sorry")

my library was defined as an empty list library=[] is my try-except block code wrong or is my donate_book code wrong?

my Book class:

 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)

I defined duplicate error as this:

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)
2

There are 2 answers

3
Christian Tapia On

I think you would like to use:

if i.book_id == book.book_id:

in your donate_book() method.

3
AudioBubble On

Redefine your donate_book method like this:

def donate_book(self, book):
    if book in self.books:
        raise DuplicateIdError()
    else:
        self.books.append(book)

In the Book class, define this method:

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

This overrides the equality test between books.