协程本质上是class?

Coroutine is a class in its nature?

我正在按照说明学习协程

def grep(pattern):
    print("Looking for %s" % pattern)  # prime it(explain shortly)
    while True:
        line = (yield) # expression
        if pattern in line:
            print(line)

测试一下

>>> g = grep("python")
>>> g.next()
Looking for python
>>> g.send("coroutine test")
>>> g.send("learning python")

似乎 yield 表达式作为 functools.partial 执行,排除它应该使用 next()

启动

此时,def grep实际上是一个class grep,因为它首先启动了一个生成器对象。

协同程序很难遵循,我对继续没有进一步副作用的正确方向的理解是因为 python 将其命名为 def 而不是 class 应该有她的理由.

It seems that a yield expression perform as a functools.partial, [except that] it should be primed using next().

我不确定是什么让你这么说,但我没有立即看到相似之处。 functools.parital 旨在将某些 args/kwargs 部分绑定到可调用对象,并让您保存其他一些 args/kwargs 以供用户调用。 (“partial() 用于部分函数应用程序,其中 'freezes' 函数参数的某些部分 and/or 关键字导致具有简化签名的新对象。”)这并不是真正发生的事情使用此生成器或任何生成器。

The coroutine is tricky to follow, is my understanding on the right direction to continue without further side-effects since Python named it def rather than class?

他们很狡猾,同意你的看法。但是我不确定我是否看到协程是怎样的 "like a class in its nature." 协程是一种专门的生成器。生成器用 def 定义并且能够暂停和恢复它们的执行。这描述的是生成器,而不是 类,对于初学者来说,仅将 def 替换为 class 在句法上是无效的。

您可以想到像 a = yield b 这样的任何表达式的一种方法是 标记一个断点。

当您调用 next(g) 时,它将继续前进,直到遇到 yield 语句,然后停在那里。它会将结果值推送到调用堆栈 它将暂停执行并停在那里,当您再次对其调用 next() 时可以恢复。 (这是函数和生成器之间以及函数和协程之间的关键区别,推而广之。)

第一次调用 next() 时,lineNone。 (基本上,line = yield None。)你将无法迭代它,因为你不能说 for pattern in None。 "priming" 在这种情况下的意思可能是指对 next(g) 的初始调用类似于 g.send(None).

现在,当您向生成器发送额外的值时,它们将被分配给 line,而 pattern 仍然是 "python." 如果 "python" 在您 .send() 中,它被打印出来。

>>> g = grep("python")
>>> n = g.send(None)  # equiv to next(g); stop at line = (yield)
Looking for python
>>> n is None
True
>>> g.send("coroutine test")
>>> g.send("coroutine test")
>>> g.send("coroutine test")  # no match
>>> g.send("learning python") # match
learning python
>>> g.send("python3.7") # match
python3.7