V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Dec 16, 2016 · 1773 views
    This topic created in 3419 days ago, the information mentioned may be changed or developed.

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

    
    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 replies    2016-12-16 20:39:33 +08:00
    introom
        1
    introom  
       Dec 16, 2016   ❤️ 1
    因为 myRange.idx 到 3 了呀。。。。
    wisefree
        2
    wisefree  
    OP
       Dec 16, 2016
    @introom 谢谢!
    wisefree
        3
    wisefree  
    OP
       Dec 16, 2016
    @introom 写着写着,人懵圈了。。。
    ```python
    def __iter__(self):
    return self
    ```
    iter(myRange)返回的是自己 myRange 。。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1478 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 17:05 · PVG 01:05 · LAX 10:05 · JFK 13:05
    ♥ Do have faith in what you're doing.