Special methods let objects work naturally with print() and len().
How does Python know what to display when we print an object or ask for its length?
class Book:
def __init__(self, title, author): self.title, self.author = title, author
def __str__(self): return f"{self.title} by {self.author}"
book = Book("Dune", "Frank Herbert")
print(book)
class BookCollection:
def __init__(self): self.books = []
def add_book(self, book): self.books.append(book)
def __len__(self): return len(self.books)
collection = BookCollection()
for title in ("Dune", "The Hobbit", "Python Basics"): collection.add_book(title)
print(len(collection))Without __str__(), print(book) usually shows an unreadable default object description. __str__() returns readable text for print(book) and str(book); it must use return, not print(). BookCollection stores books in a list, and len(collection) uses its __len__() method to return a non-negative integer. This prepares us for a Library of real Book objects in the next Composition lesson. __str__() returns a string, while __len__() returns a non-negative integer.
Dune by Frank Herbert
3Try 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, author): self.title, self.author = title, author
def __str__(self): return f"{self.title} by {self.author}"
book = Book("Dune", "Frank Herbert")
print(book)
class BookCollection:
def __init__(self): self.books = []
def add_book(self, book): self.books.append(book)
def __len__(self): return len(self.books)
collection = BookCollection()
for title in ("Dune", "The Hobbit", "Python Basics"): collection.add_book(title)
print(len(collection))Run the example, then change one value and observe the result.
