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 browser
1# Program to demonstrate some magic methods
2
3class BookCollection:
4 def __init__(self, books):
5 self.books = books
6
7 def __len__(self):
8 return len(self.books)
9
10 def __str__(self):
11 return ", ".join(self.books)
12
13bc = 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.