如何在python中使用__iter__和__next__进行迭代?

How to use __iter__ and __next__ for iteration in python?

我正在尝试根据 this 网站中的教程了解迭代器、生成器和装饰器在 python 中的工作方式。

在第一个例子中,he/she演示一个简单的例子如下:

class Count:
    def __init__(self, low, high):
        self.low = 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

问题是,我无法遍历这个class的对象:

>>> ================================ RESTART ================================
>>> 
>>> c = Count(1, 10)
>>> for i in c:
    print i



Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    for i in c:
TypeError: instance has no next() method
>>> 

怎么了?

该教程似乎适用于 Python 3

In Python 2 迭代器必须有 next() method (PEP 3114 - 重命名 iterator.next() 到 iterator.__next__()):

class Count:
    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