yield 的作用是把一个函数变成一个generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| In [1]: def foo(): ...: print("starting ...") ...: while True: ...: res = yield 4 ...: print("res: ", res) ...:
In [2]: g = foo()
In [3]: print(next(g)) starting ... 4
In [4]: print(next(g)) res: None 4
In [5]: print(type(g)) <class 'generator'>
|
调用foo()并不会执行,而是返回一个iterable对象。
1 2 3 4 5 6 7
| In [13]: for i in g: ...: i
starting ... res: None res: None res: None
|
中的来说,带有yield的函数是一个generator,直接运行foo()并不会执行函数代码,直到运行next()函数,并且后续的next()函数从foo()的yield后面开始执行。
[1] 菜鸟教程