Building Basic Iterators in Python
Suppose you have a class that encapsulates a collection of values and you want to create an iterator that allows you to access those values sequentially.
To build an iterator, implement the iterator protocol, which requires defining two methods:
1. __iter__(): Initializes and returns the iterator object itself.
2. __next__(): Returns the next value in the sequence or raises StopIteration if there are no more values.
Example Iterator:
Consider the following class with a list of values:
class Example: def __init__(self, values): self.values = values # __iter__ returns the iterable itself def __iter__(self): return self # __next__ returns the next value and raises StopIteration def __next__(self): if len(self.values) > 0: return self.values.pop(0) else: raise StopIteration()
Usage:
With this iterator, you can iterate over the values in the Example class:
e = Example([1, 2, 3]) for value in e: print("The example object contains", value)
This will print:
The example object contains 1 The example object contains 2 The example object contains 3
Iterator Customization:
As seen in the example above, the iterator's next method can control how values are fetched and returned, providing greater flexibility for customized iterators.
The above is the detailed content of How to Build Custom Iterators in Python Using `__iter__` and `__next__`?. For more information, please follow other related articles on the PHP Chinese website!