Summary of magic methods

We can summarize the concepts we described in the previous sections in the form of a cheat sheet like the one presented as follows. For each action in Python, the magic method involved is presented, along with the concept that it represents:

Statement
Magic method
Python concept

obj[key]

obj[i:j]

obj[i:j:k]

__getitem__(key)

Subscriptable object

with obj: ... __enter__ / __exit__

Context manager

for i in obj: ...

__iter__ / __next__

__len__ / __getitem__

Iterable object

Sequence

obj.<attribute>

__getattr__

Dynamic attribute retrieval

obj(*args, **kwargs)

__call__(*args, **kwargs)

Callable object

Get Clean Code in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.