Skip to content

Instantly share code, notes, and snippets.

@stephengruppetta
Created June 29, 2023 14:38
Show Gist options
  • Save stephengruppetta/b3482dac353c86c48d24f2ab304f752f to your computer and use it in GitHub Desktop.
Save stephengruppetta/b3482dac353c86c48d24f2ab304f752f to your computer and use it in GitHub Desktop.
class Book:
def __init__(self, title, author, publication_year):
self.title = title
self.author = author
self.publication_year = publication_year
def __str__(self):
return f"{self.title} by {self.author} ({self.publication_year})"
class Library:
def __init__(self):
self.books = []
def __getitem__(self, item):
if isinstance(item, int):
return self.books[item]
elif isinstance(item, str):
matching_author = [
book
for book in self.books
if item.casefold() in book.author.casefold()
]
return matching_author
def add_books(self, books):
"""
Add books to the library
:param books: list (or other sequence) of Book objects
"""
self.books.extend(books)
books_data = [
Book("To Kill a Mockingbird", "Harper Lee", 1960),
Book("1984", "George Orwell", 1949),
Book("Animal Farm", "George Orwell", 1945),
Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979),
Book("Harry Potter and the Philosopher's Stone", "J.K. Rowling", 1997),
Book("Harry Potter and the Chamber of Secrets", "J.K. Rowling", 1998),
Book("A Brief History of Time", "Stephen Hawking", 1988),
Book("The Selfish Gene", "Richard Dawkins", 1976),
Book("Cosmos", "Carl Sagan", 1980),
]
gorgeous_library = Library()
gorgeous_library.add_books(books_data)
print(gorgeous_library["Orwell"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment