迭代器和可迭代对象的疑问

2016-12-16 20:23:51 +08:00
 wisefree

看到网上的一段代码,不是很理解,>_<


class MyRange(object):
    def __init__(self, n):
        self.idx = 0
        self.n = n
        
    def __iter__(self):
        return self
        
    def __next__(self):
        if self.idx < self.n:
            val = self.idx
            self.idx += 1
            return val
        else:
            raise StopIteration()
			

if __name__ == "__main__":
    
    myRange = MyRange(3)
    
    print([i for i in myRange])# 输出:[0, 1, 2]
    # for in 执行流程如下
    # iter(myRange)
    # 执行了三次 next(myRange)
    # 遇到 StopIteration 异常后,停止循环
    
    
    print([i for i in myRange]) # 输出:[]
    
    # 为什么输出 [] 而不是 [0, 1, 2]
    # 执行流程应该还是一样的
    # iter(myRange)
    # 执行了三次 next(myRange)
    # 遇到 StopIteration 异常后,停止循环

1394 次点击
所在节点    Python
3 条回复
introom
2016-12-16 20:27:18 +08:00
因为 myRange.idx 到 3 了呀。。。。
wisefree
2016-12-16 20:38:13 +08:00
@introom 谢谢!
wisefree
2016-12-16 20:39:33 +08:00
@introom 写着写着,人懵圈了。。。
```python
def __iter__(self):
return self
```
iter(myRange)返回的是自己 myRange 。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/328166

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX