yield
语句用于函数中,将该函数转换为“生成器”(创建迭代器的函数)。通常通过调用next()
方法来恢复生成器的执行。然而,也可以通过调用send()
方法而不是next()
方法来向函数发送值以恢复它:
cr.send(1)
在您的示例中,每次都会将值1赋给c。
cr.next()
实际上等同于 cr.send(None)
。您可以使用send
函数向生成器发送值。
如果执行以下操作:
p = protocol()
p.next() # advance to the yield statement, otherwise I can't call send
p.send(5)
如果调用p.next()
,yield
将返回None
。
此外,如果yield
返回5,则生成器内部的c
将为5。
您可以在此处找到更多信息。
yield
根据生成器函数内定义的逻辑返回数据流。send(val)
是一种从生成器函数外部传递所需值的方法。p.next()
在 Python 3 中不起作用,next(p)
可以在 Python 2 和 3 中使用(内置)p.next()
在 Python 3 中无法使用,会出现以下错误,但在 Python 2 中仍然可以使用。
Error: 'generator' object has no attribute 'next'
def fun(li):
if len(li):
val = yield len(li)
print(val)
yield None
g = fun([1,2,3,4,5,6])
next(g) # len(li) i.e. 6 is assigned to val
g.send(8) # 8 is assigned to val
send()
方法之前,您必须先调用next()
方法来启动它,否则您将会收到一个 TypeError 错误,提示:TypeError: can't send non-None value to a just-started generator
。 - Caumons