One library. Different books. One working system.
Should Library inherit from Book, or should it contain Book objects?
class Book:
def __init__(self, title): self.title = title
def display_info(self): print(f"Book: {self.title}")
class EBook(Book):
def display_info(self): print(f"EBook: {self.title}")
class PrintedBook(Book):
def display_info(self): print(f"Printed book: {self.title}")
class AudioBook(Book):
def display_info(self): print(f"Audio book: {self.title}")
class Library:
def __init__(self): self.books=[]
def add_book(self, book): self.books.append(book)
def show_books(self):
for book in self.books: book.display_info()
def __len__(self): return len(self.books)
library=Library()
for book in (Book("Dune"),EBook("Python Basics"),PrintedBook("The Hobbit"),AudioBook("Python Stories")): library.add_book(book)
library.show_books()
print(f"Total books: {len(library)}")Inheritance — IS-A: EBook is a type of Book. That is why EBook inherits from Book. Composition — HAS-A: Library is not a type of Book. A Library has books and stores their objects in self.books. Objects working together: Library uses the objects it contains. When show_books() runs, each book uses its own display_info() method. The __len__() method lets us count the books with len(library).
Book: Dune
EBook: Python Basics
Printed book: The Hobbit
Audio book: Python Stories
Total books: 4Try changing one value, then explain which part of the collection changed and why.
Keep this in mind: Read the collection operation before predicting the result.
class Book:
def __init__(self, title): self.title = title
def display_info(self): print(f"Book: {self.title}")
class EBook(Book):
def display_info(self): print(f"EBook: {self.title}")
class PrintedBook(Book):
def display_info(self): print(f"Printed book: {self.title}")
class AudioBook(Book):
def display_info(self): print(f"Audio book: {self.title}")
class Library:
def __init__(self): self.books=[]
def add_book(self, book): self.books.append(book)
def show_books(self):
for book in self.books: book.display_info()
def __len__(self): return len(self.books)
library=Library()
for book in (Book("Dune"),EBook("Python Basics"),PrintedBook("The Hobbit"),AudioBook("Python Stories")): library.add_book(book)
library.show_books()
print(f"Total books: {len(library)}")Run the example, then change one value and observe the result.
