class Book(object): \"\"\"A Book Object.\"\"\" def __init__(self, title, author,
ID: 3848381 • Letter: C
Question
class Book(object):
"""A Book Object."""
def __init__(self, title, author, pub_yr='Unknown'):
self.title = title
self.author = author
self.pub_yr = pub_yr
def __repr__(self):
return '<Book. Title: %s.>' % (self.title)
class Library(object):
"""A collection of book objects."""
def __init__(self):
self.books = []
def __repr__(self):
return '<Library containing %s book(s).>' % (len(self.books))
def list_books(self):
"""List all the books in the library."""
if len(self.books) == 0:
print "Library is empty."
return
for book in self.books:
print book.title
print ' Author:', book.author
print ' Published:', book.pub_yr
print
def add_book(self, book):
"""Add a book to the library."""
if not isinstance(book, Book):
raise Exception('Please enter a Book Object to add to the library')
self.books.append(book)
print 'Added: %s' % (book.title)
def empty_library(self):
"""Remove all books from the library."""
pass
########### WRITE YOUR SCRIPT HERE
# Details on what the script should include are in the skills assessment
# instructions.
b1 =Book("The Bell Jar", "Sylvia Plath", 1963)
#printing book1 information
print " Book b1 : ",b1
print 'Book b1 Publication year : ',b1.pub_yr
b2 =Book("Anna Karenina", "Leo Tolstoy")
#printing b2 information
print' '
print "Book b2 : ",b2
print 'Book b2 Publication year : ',b2.pub_yr
#Instantiate a library object
l = Library()
print(l)
# Adding books to Library
l.add_book(b1);
l.add_book(b2);
print " "
# Listing books
l.list_books();
Question:
Finish the empty_library method in the Library class. It should remove all the books from a library.
Call the empty_library method at the bottom of the script you wrote in Part One. Then, call the method that lists the books in a library and verify that it shows that the library is now empty.
Explanation / Answer
Hi,
I have modified the code to implement empty_library method as well done some refactoring.
Given below is the modified code. Feel free to comment if you have any queries. Also give a thumbs up if the answer helped you.
#code starts here
#code ends here
Sample output
-------------------------------------------
Book b1 : <Book. Title: The Bell Jar.>
Book b1 Publication year : 1963
Book b2 : <Book. Title: Anna Karenina.>
Book b2 Publication year : Unknown
<Library containing 0 book(s).>
Added: The Bell Jar
Added: Anna Karenina
The Bell Jar
Author: Sylvia Plath
Published: 1963
Anna Karenina
Author: Leo Tolstoy
Published: Unknown
Library is empty.
-------------------------------------------
Hope it Helps!
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.