Yield 作为赋值有什么作用? myVar =(产量)
我熟悉 Yield 返回值,这主要归功于 这个问题< /a>
但是当yield 位于赋值的右侧时它会做什么呢?
@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'm familiar with yield to return a value thanks mostly to this question
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
函数中使用的
yield
语句将该函数转变为“生成器”(创建迭代器的函数)。生成的迭代器通常通过调用 next() 来恢复。但是,可以通过调用方法send()
而不是next()
来将值发送到函数来恢复它:在您的示例中,这将分配值
1 到
c
。cr.next()
实际上等同于cr.send(None)
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 callingnext()
. However it is possible to send values to the function by calling the methodsend()
instead ofnext()
to resume it:In your example this would assign the value
1
toc
each time.cr.next()
is effectively equivalent tocr.send(None)
您可以使用
send
函数将值发送到生成器。如果你执行:
那么
yield
将返回 5,所以在生成器内c
将是 5。另外,如果你调用
p.next()
,yield
将返回None
。您可以在此处找到更多信息。
You can send values to the generator using the
send
function.If you execute:
then
yield
will return 5, so inside the generatorc
will be 5.Also, if you call
p.next()
,yield
will returnNone
.You can find more information here.
yield
根据生成器函数中定义的逻辑返回数据流。p.next() 在 python3 中不起作用,next(p) 对 python 2,3 都有效(内置)
p.next() 不适用于 python 3,给出以下错误,但它仍然有效在 python 2 中。
这是一个演示:
yield
returns a stream of data as per the logic defined within the generator function.p.next() doesn't work in python3, next(p) works (built-in) for both python 2,3
p.next() doesn't work with python 3, gives the following error,however it still works in python 2.
Here's a demonstration: