python的生成器与yield


一个包含yield的函数,执行后可以获取一个需要next来推动执行的代码流。
代码流好比牙膏,next好比在挤牙膏。
def odd():
    print('step 1')
    yield 1
    print('step 2')
    yield(3)
    print('step 3')
    yield(5)

 

调用该generator时,首先要生成一个generator对象,然后用next()函数不断获得下一个返回值:

>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

 

posted @ 2017-12-26 20:57  Valentino  阅读(250)  评论(0编辑  收藏  举报