我正在查看http://www.dabeaz.com/coroutines/ ,我觉得这很有趣,但在一个例子中有一个我不理解的行为。
在 bogus.py此处报告的示例
# bogus.py
#
# Bogus example of a generator that produces and receives values
def countdown(n):
print "Counting down from", n
while n >= 0:
newvalue = (yield n)
# If a new value got sent in, reset n with it
if newvalue is not None:
n = newvalue
else:
n -= 1
# The holy grail countdown
c = countdown(5)
for x in c:
print x
if x == 5:
c.send(3)
生成的数字序列是 5, 2, 1, 0,我不明白数字 3 去了哪里:在 send(3)
之后,变量 n
设置正确,但在第二次执行 yield
时,看起来值 3 只是未在 for 循环中生成。
有人可以解释一下为什么会发生这种情况吗?
最佳答案
3
从 .send()
返回,但被丢弃。发电机产生 5
, 3
, 2
, 1
, 0
;但因为3
返回到.send()
调用您看不到打印的值。 for
循环永远看不到它。
发生的事情是这样的:
- 第一次
for
循环调用next()
在生成器上,代码前进直到5
已产生。 -
x == 5
是True
,所以c.send(3)
叫做。代码通过生成器函数前进,并且newvalue
设置为3
. - 生成器不会在那里暂停,它现在拥有控制权。发电机运行通过
while
循环并返回到(yield n)
表达。3
已产生。它成为c.send(3)
的返回值。返回值在这里被丢弃。 for
循环继续,调用next()
再次。生成器再次继续yield
返回None
,循环舍入到n -= 1
并产生2
.for
循环继续调用next()
在发电机上,1
和0
产生,生成器结束。
引自 generator.send()
documentation :
Resumes the execution and “sends” a value into the generator function. The
value
argument becomes the result of the currentyield
expression. Thesend()
method returns the next value yielded by the generator, or raisesStopIteration
if the generator exits without yielding another value.
强调我的。
关于python - python 生成器/协程中的值丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17990624/