定义迭代器类的Python,失败,"iter()返回类型为'Fib'的非迭代器"

Tro*_*yvs 15 python types iterator exception ipython

我正在使用python 2.7和ipython2.7.在ipython中我尝试过:

class Fib(object):
    def __init__(self, max):
        super(Fib, self).__init__()
        self.max = max

    def __iter__(self):
        self.a = 0
        self.b = 1
        return self

    def __next__(self):
        fib = self.a
        if fib > self.max:
            raise StopIteration
        self.a, self.b = self.b, self.a + self.b
        return fib

def main():
    fib = Fib(100)
    for i in fib:
        print i

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

那么它报告错误:

类型错误回溯(最近通话最后一个)在()22 23如果名称 == ' 主要 ':---> 24主()25

<ipython-input-21-f10bd2d06666> in main()
    18 def main():
    19     fib = Fib(100)
---> 20     for i in fib:
    21         print i
    22

TypeError: iter() returned non-iterator of type 'Fib'
Run Code Online (Sandbox Code Playgroud)

这段代码实际上来自互联网.语法对我来说似乎没问题,但问题是如何发生的?

谢谢.

Kro*_*ack 35

def __next__(self) 适用于Python 3

对于Python 2,您需要添加方法 next()

此代码将在Python 3和Python 2下运行:

class Fib(object):
    def __init__(self, max):
        super(Fib, self).__init__()
        self.max = max

    def __iter__(self):
        self.a = 0
        self.b = 1
        return self

    def __next__(self):
        fib = self.a
        if fib > self.max:
            raise StopIteration
        self.a, self.b = self.b, self.a + self.b
        return fib

    def next(self):
        return self.__next__()


def main():
    fib = Fib(100)
    for i in fib:
        print(i)

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)