Python : 迭代器Iterators

Python 迭代器对象需要支持两个方法.

iter(),返回迭代器对象自身. 用于for x in 中.
next(),放回迭代器的下一个值.如果没有下一个值可以返回,那么需要抛出StopIteration异常.

class Counter(object):
    def __init__(self, low, high):
        self.current = low
        self.high = high
    def __iter__(self):
        return self
    def __next__(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1
>>> c = Counter(5, 8)
>>> for i in c:
        print(i, end=' ')
5 6 7 8
迭代器只能被使用一次.抛出StopIteration 异常后会持续抛出相同异常.

你可能感兴趣的:(Python : 迭代器Iterators)