This exercise combines two classes: one for a record, one that manages a list of them.
Book whose __init__ takes title and author and stores both.Library:__init__ takes no arguments besides self and sets a books attribute to an empty list.add with one parameter, book, appends it to books.titles_by with one parameter, author. It returns a list of the titles of that author's books, in the order added.book_count that returns the number of books.library = Library()
library.add(Book("Emma", "Austen"))
library.add(Book("Dracula", "Stoker"))
library.add(Book("Persuasion", "Austen"))
print(library.titles_by("Austen"))
Output:
['Emma', 'Persuasion']
Run your code to see the output, then press Submit.
titles_by is the filter pattern from the objects-in-lists lesson.Library stores Book objects, not titles — extract .title only when returning.import unittest
class TestLibrary(unittest.TestCase):
def make_library(self):
library = Library()
library.add(Book("Emma", "Austen"))
library.add(Book("Dracula", "Stoker"))
library.add(Book("Persuasion", "Austen"))
return library
def test_new_library_is_empty(self):
self.assertEqual(Library().book_count(), 0)
def test_book_count_after_adding(self):
self.assertEqual(self.make_library().book_count(), 3)
def test_titles_by_austen_in_order(self):
self.assertEqual(self.make_library().titles_by("Austen"), ["Emma", "Persuasion"])
def test_titles_by_unknown_author_is_empty(self):
self.assertEqual(self.make_library().titles_by("Tolstoy"), [])
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
class Library:
def __init__(self):
self.books = []
def add(self, book):
self.books.append(book)
def titles_by(self, author):
return [book.title for book in self.books if book.author == author]
def book_count(self):
return len(self.books)
library = Library()
library.add(Book("Emma", "Austen"))
library.add(Book("Dracula", "Stoker"))
library.add(Book("Persuasion", "Austen"))
print(library.titles_by("Austen"))
print(library.book_count())
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.