分配产生的收益是什么? myVar =(收益) [英] what does yield as assignment do? myVar = (yield)
问题描述
但是在作业右侧时,yield会做什么?
but what does yield do when it is on the right side of an assignment?
@coroutine
def protocol(target=None):
while True:
c = (yield)
def coroutine(func):
def start(*args,**kwargs):
cr = func(*args,**kwargs)
cr.next()
return cr
return start
我在此博客,同时研究状态机和协同程序.
I came across this, on the code samples of this blog, while researching state machines and coroutines.
推荐答案
函数中使用的yield
语句将该函数转换为生成器"(创建迭代器的函数).通常通过调用next()
恢复生成的迭代器.但是,可以通过调用方法send()
而不是next()
来将值发送到函数以恢复它:
The yield
statement used in a function turns that function into a "generator" (a function that creates an iterator). The resulting iterator is normally resumed by calling next()
. However it is possible to send values to the function by calling the method send()
instead of next()
to resume it:
cr.send(1)
在您的示例中,这将每次将1
值分配给c
.
In your example this would assign the value 1
to c
each time.
cr.next()
实际上等效于cr.send(None)
这篇关于分配产生的收益是什么? myVar =(收益)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!