Make sure to put the main section of your code in the following if block: (1) Bu
ID: 3706806 • Letter: M
Question
Make sure to put the main section of your code in the following if block:
(1) Build the Book class with the following specifications:
Attributes
title (str)
author (str)
publisher (str)
copyright (str)
Create a constructor that has 4 parameters (in addition to self). Set each of the constructor parameters to the default value ‘’ (empty string)
Define a __str__() method to print a Book like the following
(2) In the main section of your code, read in the file books.txt. Create a list called library. Create books from the file and add them to the library.
(3) Print the library as follows.
The library has 3 books:
Title: Java Software Solutions
Author: Lewis & Loftus
Publisher: Addison-Wesley Copyright: 2012
Title: Faces in Time
Author: Lewis Aleman
Publisher: Megalodon Entertainment Copyright: 2010
Title: Purple Cow
Author: Seth Godin
Publisher: Portfolio Copyright: 2002
Explanation / Answer
class Book: def __init__(self, title, author, publisher, copyright): self.title = title self.author = author self.publisher = publisher self.copyright = copyright def __str__(self): return 'Title: %s Author:%s Publisher: %s Copyright:%s' % (self.title, self.author, self.publisher, self.copyright) def main(): books = [] with open('books.txt', 'r') as f: for line in f: words = line.strip().split(',') books.append(Book(words[0].strip(), words[1].strip(), words[2].strip(), words[3].strip())) print('The library has %d books:' % len(books)) for book in books: print(book) print() if __name__ == '__main__': main()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.