python 中的协程
我从一本书上读到了以下代码,并对此有一些疑问。
def coroutine(func):
def start(*args, **kwargs):
g = func(*args, **kwargs)
g.next()
return g
return start
@coroutine
def receiver():
print("Ready to receive")
while True:
n = (yield)
print("Got %s" % n)
r = receiver()
r.send("hello, world")
通过使用协程
,不需要初始.next()
。我的理解是,如果r = receive()
,则r = start
,所以当我调用r.send()
时,它等于start.send()
,然后我再次调用.next()
,对吗?但结果并不是我所期望的。
I read the following code from a book, and have some questions about it.
def coroutine(func):
def start(*args, **kwargs):
g = func(*args, **kwargs)
g.next()
return g
return start
@coroutine
def receiver():
print("Ready to receive")
while True:
n = (yield)
print("Got %s" % n)
r = receiver()
r.send("hello, world")
By using coroutine
, no initial .next()
is needed. My understanding is, if r = receiver()
, then r = start
, so when I call r.send()
, it equals to start.send()
, then I call .next()
again, right? But the result is not what I expected.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题不是协程。您误解了函数装饰器。在
r = receive()
之后,r不是start而是g。阅读一下函数装饰,你就会明白发生了什么。Your problem isn't the coroutine. You're misunderstanding the function decorator. After
r = receiver()
, r is not start but g. Read up on function decoration and you'll understand what is going on.