【发布时间】:2013-08-02 04:09:50
【问题描述】:
我正在查看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 循环。
有人能解释一下为什么会这样吗?
【问题讨论】:
标签: python iteration generator coroutine