当前位置:网站首页>TypeError: iter() returned non-iterator of type ‘xxx‘

TypeError: iter() returned non-iterator of type ‘xxx‘

2022-06-21 06:01:00 Channing Lewis

最近在读《Python高级编程》(Ziade著),看到里面的自我设计的迭代器:
在这里插入图片描述
自己写的:

class MyIter:
    def __init__(self,step):
        self.step=step
    def __iter__(self):
        return self
    def next(self):
        if self.step==0:
            raise StopIteration
        self.step-=1
        return self.step

for i in MyIter(5):
    print(i)

跑的时候报错:
TypeError: iter() returned non-iterator of type ‘xxx’

因为我用的是Python3,所以next应该是__next__,改了之后就正常了。

原网站

版权声明
本文为[Channing Lewis]所创,转载请带上原文链接,感谢
https://blog.csdn.net/lycwhu/article/details/125284610