Python3关与迭代器next()使用为__next__()的一点注意事项

class Fibs:
    def __init__ (self):
        self.a =0
        self.b =1
    def next(self):
        self.a , self.b = self.b, self.a+self.b
        return self.a
    def __iter__(self):
        return self
关于如上Python2 代码中迭代器的使用,引用时用*.next()的方式在Python3中不再有效,而是会报错:
Traceback (most recent call last):
  File "", line 1, in 
    it.next()
AttributeError: 'list_iterator' object has no attribute 'next'
正确改进为:
class Fibs:
    def __init__ (self):
        self.a =0
        self.b =1
    def __next__(self):
        self.a , self.b = self.b, self.a+self.b
        return self.a
    def __iter__(self):
        return self
以next(it)的形式进行引用

你可能感兴趣的:(Python)