Creating Iterators in Python
Python iterators are objects that adhere to the iterator protocol, featuring the __iter__() and __next__() methods.
iter Method:
The __iter__() method returns the iterator object, automatically invoked at the start of loops.
next Method:
The __next__() method retrieves the subsequent value and is implicitly called during loop increments. It raises a StopIteration exception when no more values are available, which is detected by loop constructs and used to cease iteration.
For instance, consider the following simplistic counter class:
class Counter: def __init__(self, low, high): self.current = low - 1 self.high = high def __iter__(self): return self def __next__(self): # Python 2: def next(self) self.current += 1 if self.current < self.high: return self.current raise StopIteration
When utilizing the Counter:
for c in Counter(3, 9): print(c)
The output will be:
3 4 5 6 7 8
Alternatively, generators offer a simpler approach to iterator creation:
def counter(low, high): current = low while current < high: yield current current += 1
Employing the generator:
for c in counter(3, 9): print(c)
Produces identical output. Internally, the generator resembles the Counter class, supporting the iterator protocol.
For a comprehensive overview of iterators, please refer to David Mertz's article, "Iterators and Simple Generators."
The above is the detailed content of How Do Python's `__iter__` and `__next__` Methods Enable Iterator Creation?. For more information, please follow other related articles on the PHP Chinese website!