Different objects can respond to the same method call in their own way.
Book, EBook, and PrintedBook can now be handled together. How can one loop work with different kinds of books without checking their types?
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}")
books = [Book("Dune"), EBook("Python Basics"), PrintedBook("The Hobbit")]
for book in books:
book.display_info()Every object has display_info(). The call is the same, but Python chooses the implementation from the object’s real type. The loop variable name does not choose the method. Inheritance gives EBook Book attributes and methods. Method overriding gives EBook its own display_info(). Polymorphism lets the same display_info() call work with each object and produce its own result.
Book: Dune
EBook: Python Basics
Printed book: The HobbitTry 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}")
books = [Book("Dune"), EBook("Python Basics"), PrintedBook("The Hobbit")]
for book in books:
book.display_info()Run the example, then change one value and observe the result.
