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 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.

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.