您的位置:首页 > 编程语言 > Python开发

python的生成器与yield

2017-12-26 20:57 411 查看

一个包含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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: