Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to successfully "donate a book" as a function within a class
    text
    copied!<p>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.</p> <pre><code> 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) </code></pre> <p>This is my try-except block:</p> <pre><code> try: donate_book(book) print("Thank you for your Donation!") except: print ("that id# is already taken, sorry") </code></pre> <p>my library was defined as an empty list library=[] is my try-except block code wrong or is my donate_book code wrong?</p> <p>my Book class:</p> <pre><code> 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) </code></pre> <p>I defined duplicate error as this:</p> <pre><code>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) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload