Magic Methods Overview in Python
Show common magic methods like __str__ and __len__.
IntermediateObject-Oriented ProgramsExample 18 of 25
magic-methods-overview.py
Run in browser1# 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.