V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wisefree
V2EX  ›  Python

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

  •  
  •   wisefree · 2016-12-16 20:23:51 +08:00 · 1378 次点击
    这是一个创建于 2700 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    
    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 异常后,停止循环
    
    
    3 条回复    2016-12-16 20:39:33 +08:00
    introom
        1
    introom  
       2016-12-16 20:27:18 +08:00   ❤️ 1
    因为 myRange.idx 到 3 了呀。。。。
    wisefree
        2
    wisefree  
    OP
       2016-12-16 20:38:13 +08:00
    @introom 谢谢!
    wisefree
        3
    wisefree  
    OP
       2016-12-16 20:39:33 +08:00
    @introom 写着写着,人懵圈了。。。
    ```python
    def __iter__(self):
    return self
    ```
    iter(myRange)返回的是自己 myRange 。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1012 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 20:44 · PVG 04:44 · LAX 13:44 · JFK 16:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.