Magic Methods Overview in Python
Show common magic methods like __str__ and __len__.
IntermediateObject-Oriented ProgramsExample 18 of 25
magic-methods-overview.py
1# Program to demonstrate some magic methods23class BookCollection:4 def __init__(self, books):5 self.books = books67 def __len__(self):8 return len(self.books)910 def __str__(self):11 return ", ".join(self.books)1213bc = BookCollection(["Python 101", "OOP in Python"])14print(len(bc))15print(bc)
Output
2 Python 101, OOP in Python
What's going on
Implementing __len__ and __str__ customizes how len() and print() behave for the class.
After this program
If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.