Question
How would one create an iterative function (or iterator object) in python?
How-To
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and next(). The __iter__ returns the iterator object and is implicitly called at the start of loops. The next() method returns the next value and is implicitly called at each loop increment. next() raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.
Here's a simple example of a counter:
- class Counter:
- def __init__(self, low, high):
- self.current = low
- self.high = high
- def __iter__(self):
- return self
- def next(self): # Python 3: def __next__(self)
- if self.current > self.high:
- raise StopIteration
- else:
- self.current += 1
- return self.current - 1
- for c in Counter(3, 8):
- print c
This is easier to write using a generator, as covered in a previous answer:
- def counter(low, high):
- current = low
- while current <= high:
- yield current
- current += 1
- for c in counter(3, 8):
- print c
David Mertz's article, Iterators and Simple Generators, is a pretty good introduction.
Supplement
* FAQ - What makes something iterable in python
* FAQ - In Python, how do I determine if an object is iterable?
沒有留言:
張貼留言