August 2018
Intermediate to advanced
332 pages
9h 12m
English
When we try to iterate an object, Python will call the iter() function over it. One of the first things this function checks for is the presence of the __iter__ method on that object, which, if present, will be executed.
The following code creates an object that allows iterating over a range of dates, producing one day at a time on every round of the loop:
from datetime import timedeltaclass DateRangeIterable: """An iterable that contains its own iterator object.""" def __init__(self, start_date, end_date): self.start_date = start_date self.end_date = end_date self._present_day = start_date def __iter__(self): return self def __next__(self): if self._present_day >= self.end_date: raise StopIteration today = self._present_day ...