简体   繁体   English

python中的协程

[英]Coroutines in python

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. 通过使用coroutine ,不需要初始的.next() 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? 我的理解是,如果r = receiver() ,则r = start ,所以当我调用r.send() ,它等于start.send() ,然后我再次调用.next() ,对吗? But the result is not what I expected. 但是结果却不是我所期望的。

Your problem isn't the coroutine. 您的问题不是协程。 You're misunderstanding the function decorator. 您误会了函数装饰器。 After r = receiver() , r is not start but g. r = receiver() ,r不是g而是开始。 Read up on function decoration and you'll understand what is going on. 阅读功能装饰,您将了解发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM