为什么在Python中需要协程?

编程入门 行业动态 更新时间:2024-10-24 21:22:29
本文介绍了为什么在Python中需要协程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我很早以前就听说过协同例程,但从未使用过。据我所知,协同例程类似于生成器。

I've heard about co-routines long ago, but never used them. As I know, co-routines are similar to generators.

为什么我们需要Python中的协同例程?

Why do we need co-routines in Python?

推荐答案

Generator 使用yield返回值。 Python生成器函数还可以使用(yield)语句使用值。另外,生成器对象上的两个新方法 send()和 close()创建了一个框架,用于消耗对象并产生价值。定义这些对象的生成器函数称为协程。

Generator uses yield to return values. Python generator functions can also consume values using a (yield) statement. In addition two new methods on generator objects, send() and close(), create a framework for objects that consume and produce values. Generator functions that define these objects are called coroutines.

协程使用(收益)语句消耗值,如下所示:

Coroutines consume values using a (yield) statement as follows:

value = (yield)

使用这种语法,执行在此语句处暂停直到使用参数调用对象的send方法:

With this syntax, execution pauses at this statement until the object's send method is invoked with an argument:

coroutine.send(data)

然后,恢复执行,并将值分配给数据值。为了表示计算结束,我们使用 close()方法关闭了协程。这会在协程内部引发GeneratorExit异常,我们可以使用try / except子句捕获该异常。

Then, execution resumes, with value being assigned to the value of data. To signal the end of a computation, we shut down a coroutine using the close() method. This raises a GeneratorExit exception inside the coroutine, which we can catch with a try/except clause.

下面的示例说明了这些概念。这是一个协程,可以打印与提供的模式匹配的字符串。

The example below illustrates these concepts. It is a coroutine that prints strings that match a provided pattern.

def match(pattern): print('Looking for ' + pattern) try: while True: s = (yield) if pattern in s: print(s) except GeneratorExit: print("=== Done ===")

我们用模式,然后调用 __ next __()开始执行:

We initialize it with a pattern, and call __next__() to start execution:

m = match("Jabberwock") m.__next__() Looking for Jabberwock

对 __ next __()的调用导致函数主体被执行,因此寻找jabberwock行被打印出来。执行将继续直到遇到 line =(yield)语句。然后,执行暂停,并等待将值发送给m。我们可以使用 send()向其发送值。

The call to __next__() causes the body of the function to be executed, so the line "Looking for jabberwock" gets printed out. Execution continues until the statement line = (yield) is encountered. Then, execution pauses, and waits for a value to be sent to m. We can send values to it using send().

更多推荐

为什么在Python中需要协程?

本文发布于:2023-11-23 10:01:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621036.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!