Practice: Library

Practice: Library

This exercise combines two classes: one for a record, one that manages a list of them.

Exercise

  1. Define a class named Book whose __init__ takes title and author and stores both.
  2. Define a class named Library:
  3. __init__ takes no arguments besides self and sets a books attribute to an empty list.
  4. A method named add with one parameter, book, appends it to books.
  5. A method named titles_by with one parameter, author. It returns a list of the titles of that author's books, in the order added.
  6. A method named 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.

Hints

  • titles_by is the filter pattern from the objects-in-lists lesson.
  • Library stores Book objects, not titles — extract .title only when returning.

Tests

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())
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.