Pythonisms
Enriching Your Python Classes With Dunder (Magic, Special) Methods
What Are Dunder Methods
In Python, special methods are a set of predefined methods you can use to enrich your classes. They are easy to recognize because they start and end with double underscores, for example __init__
or __str__
.
examples
-
you can add a
__len__
dunder method to your class to make it return something withlen()
-
You can implement a
__getitem__
method which allows you to use Python’s list slicing syntax:obj[start:stop]
.
Object Representation: str, repr
It’s common practice in Python to provide a string representation of your object for the consumer of your class (a bit like API documentation.)
There are two ways to do this using dunder methods:
-
__repr__
: The “official” string representation of an object. This is how you would make an object of the class. The goal of__repr__
is to be unambiguous. -
__str__
: The “informal” or nicely printable string representation of an object. This is for the enduser.
Python Iterators
Objects that support the __iter__
and __next__
dunder methods automatically work with for-in loops.