python中如何创建一个迭代器

2022-04-15 - Python开发
311

python中如何创建一个迭代器,给出了测试代码
迭代器的类必须包含两个方法; iter() and next().
下面是一个自定义的奇数迭代器

class OddIterator(object):
    def __init__(self):
        self.value = -1
    # Required for the for-in syntax
    def __iter__(self):
        return self
    # Returns the next value of the iterator
    def next(self):
        self.value += 2
        return self.value

测试迭代器的next方法

iter = OddIterator()
assert iter.next() == 1
assert iter.next() == 3
assert iter.next() == 5
assert iter.next() == 7

测试for in 语法是否正确

iter = OddIterator()
# Prints 1, 3, 5, 7 and 9
for i in iter:
    print i
    if i >= 9:
        break