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

时间:2015-09-12 04:32:45

标签: python python-2.7 iterator iteration

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

在第一个例子中,他/她演示了一个简单的例子如下:

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

问题是,我无法迭代这个类的对象:

>>> ================================ 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
>>> 

出了什么问题?

1 个答案:

答案 0 :(得分:4)

该教程似乎适用于Python 3

在Python 2中,迭代器必须具有next()方法(PEP 3114 - 将iterator.next()重命名为迭代器.__ 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