我很早以前就听说过协同例程,但从未使用过。据我所知,协同例程类似于生成器。
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中需要协程?
发布评论