python 中的协程

发布于 2024-12-12 05:27:31 字数 570 浏览 6 评论 0原文

我从一本书上读到了以下代码,并对此有一些疑问。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素衣风尘叹 2024-12-19 05:27:31

你的问题不是协程。您误解了函数装饰器。在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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文