yield 包含两层意思,产出和让步

产出,yield 会产出一个值,提供给next()的调用方

让步,每次都会暂停执行,将控制权交给调用方,让调用方继续执行,知道需要另一个值的时候,再调用next()。调用方会从生成器拉取值。

 

从根本上把yield看做一种流程控制方式,协程是指一个过程,这个过程与调用方协作,产出由调用方提供的值。

 

yield from 更合适的关键字可能是await, 

 

When you call a function that contains a yield statement anywhere, you get a generator object, but no code runs. Then each time you extract an object from the generator, Python executes code in the function until it comes to a yield statement, then pauses and delivers the object. When you extract another object, Python resumes just after the yieldand continues until it reaches another yield (often the same one, but one iteration later). This continues until the function runs off the end, at which point the generator is deemed exhausted. – Matthias Fripp

from:

https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do

posted on 2017-08-28 11:27  Go_Forward  阅读(129)  评论(0编辑  收藏  举报