Special methods, predefined, to enrich classes in Python. They have the double underscores before and after the letters in the method name. Sometimes called "magic methods". Allows the mimicking of built-in methods (like defining __len__()
for an object some len()
can be called on it).
Dunder Methods allow for:
- Initialization of new objects with
__init__
- Object representation with
__str__
and__repr__
- Iteration with
__len__
,__getitem__
,__reversed__
- Operator overloading (comparison) with
__eq__
,__lt__
- Operator overloading (addition) with
__add__
- Method invocation with
__call__
- Context manager support (with statement) with
__enter__
,__exit__
Two key phrases in Python's iterator protocol:
- first setting up and retrieving the iterator object with an
iter()
call, and then repeatedly fetching values from it vianext()
.
While they could exist in different classes, the responsibilities can also be merged into / shouldered by a single class.
The StopIteration
exception can be used in the case of breaking out of infinite repetition involving interators.
Between Python 2 and Python 3:
- In Python 3, the method that retrieves the next value from an iterator is called next.
- In Python 2, the same method is called next (no underscores).
- Generator functions are syntactic sugar for writing objects that support the iterator protocol. Generators abstract away much of the boilerplate code needed when writing class-based iterators.
- The yield statement allows you to temporarily suspend execution of a generator function and to pass back values from it.
- Generators start raising StopIteration exceptions after control flow leaves the generator function by any means other than a yield statement.