In: Computer Science
Write a Python class to represent a LibraryMember that takes books from a library. A member has four private attributes, a name, an id, a fine amount, and the number of books borrowed. Your program should have two functions to add to the number of books and reduce the number of books with a member. Both functions, to add and return books, must return the final number of books in hand. Your program should print an error message whenever the member tries to take more than 3 books with the message “Note: You cannot have more than 3 books.” and return the value -1.
The following test case reveals the use of the class. Define a Python class to match the test case given below.
#Test: Do NOT change this code
member1 = LibraryMember()
member1.setName("John")
member1.setID("4521")
member1.setBooks(2) # set number of books in hand
member1.setFine(27.5) # set fine amount
print(member1.showInfo()) # Shows all the information of a member
print("Books in hand:", member1.returnBook(2)) # Return 2 books
member2 = LibraryMember("Mariam",
"4531", 5)
print("Books in hand:", member2.takeBook(6)) # Take 6 books
This is the Python class created as per the given requirements.
I have created all the required functions and the private data members and also tested it with the given statements.
Thank you.
class LibraryMember:
def __init__(self,name = "",id = "",books = 0,fine_amt = 0.0):
self.name = name
self.id = id
self.fine_amt = fine_amt
self.books = books
def setName(self,name):
self.name = name
def setID(self,id):
self.id = id
def setBooks(self,books):
self.books = books
def setFine(self,fine_amt):
self.fine_amt = fine_amt
def takeBook(self,newBooks):
if(newBooks>3):
print("Note: You cannot have more than 3 books.")
return -1
else:
self.books = self.books + newBooks
return self.books
def returnBooks(self,retBook):
if(retBook>self.books):
print("Books to be returned is greater than the number of books taken!")
return -1
else:
self.books = self.books - retBook
return self.books
def showInfo(self):
info = {"Name":self.name,"ID":self.id,"Fine Amount": self.fine_amt,"Books": self.books}
return info
member1 = LibraryMember()
member1.setName("John")
member1.setID("4521")
member1.setBooks(2)
member1.setFine(27.5)
print(member1.showInfo())
print("Books in hand: ",member1.returnBooks(2))
member2 = LibraryMember("Mariam","4531",5)
print("Books in hand:",member2.takeBook(6))