...

/

Summary of Magic Methods

Summary of Magic Methods

Get a summarized overview of magic methods in Python.

We can summarize the concepts we have learned 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:

Magic methods and their behaviour in Python

Statement

Magic Method

Behavior

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

The best way to implement these methods correctly (and to know the set of methods that need to be implemented together) is to declare our class to implement the corresponding class following the ...