迭代器内的变量是怎么保存的? - V2EX
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
flowarmor

迭代器内的变量是怎么保存的?

  •  
  •   flowarmor Feb 17, 2018 4468 views
    This topic created in 2994 days ago, the information mentioned may be changed or developed.

    有下面一段代码,分别打印 1 1 2 3 5 和 0 0 0 0 0,请问后面一个迭代器为什么不会打印 0 1 2 3 4 ?

    class Fib(object): def __init_(self): self.prev = 0 self.curr = 1 def next(self): value = self.curr self.curr += self.prev self.prev = value return value def __iter__(self): return self class T(object): def __iter__(self): return self def next(self): for i in range(5): return i f = Fib() t = T() print next(f) print next(f) print next(f) print next(f) print next(f) print next(t) print next(t) print next(t) print next(t) print next(t) 
    Supplement 1    Feb 17, 2018
    已结,大半夜大脑短路问了这么个问题。
    12 replies    2018-02-23 17:07:02 +08:00
    quinoa42
        1
    quinoa42  
       Feb 17, 2018
    因为已经 return 了,后面 i=1,2,3,4 根本不会运行
    wwqgtxx
        2
    wwqgtxx  
       Feb 17, 2018 via iPhone
    yield 才是给迭代器用的
    KKKKKK
        3
    KKKKKK  
       Feb 17, 2018 via Android
    查一查 magic method

    Next 调用的是 __next__ 这个方法
    lrxiao
        4
    lrxiao  
       Feb 17, 2018
    generator_instance.gi_frame.f_locals
    flowarmor
        5
    flowarmor  
    OP
       Feb 17, 2018
    @quinoa42 但是第一个 Fib 的实例就运行了。
    flowarmor
        6
    flowarmor  
    OP
       Feb 17, 2018
    @wwqgtxx 迭代器只要求有 next 和__iter__,yield 是给生成器函数用的。
    flowarmor
        7
    flowarmor  
    OP
       Feb 17, 2018
    @KKKKKK __next__是 Python 3 的方法,Python 2 的叫 next。
    ch3nOr
        8
    ch3nOr  
       Feb 17, 2018
    #1 说的对,每次你用 next(t) 的候,就用一次 t.next()。你可以在[]( http://pythontutor.com/visualize.html) 下你的代,可化你的行步。
    wallriding
        9
    wallriding  
       Feb 17, 2018
    for i in range(5):
    return i

    楼主你再看看?
    ch3nOr
        10
    ch3nOr  
       Feb 17, 2018
    Fib 的,了前迭代的,所以完全
    flowarmor
        11
    flowarmor  
    OP
       Feb 17, 2018
    @wallriding 嗯哼,昨夜太困大脑短路了。
    frostming
        12
    frostming  
       Feb 23, 2018
    @flowarmor
    迭代器只要求有 next 和__iter__,yield 是给生成器函数用的。

    一般也是用 yield 实现 next,用 return 不是不行,多麻烦啊