【发布时间】:2017-12-24 06:06:01
【问题描述】:
阅读 Python 协程时,我遇到了这段代码:
def countdown(n):
print("Start from {}".format(n))
while n >= 0:
print("Yielding {}".format(n))
newv = yield n
if newv is not None:
n = newv
else:
n -= 1
c = countdown(5)
for n in c:
print(n)
if n == 5: c.send(2)
奇怪的输出:
Start from 5
Yielding 5
5
Yielding 3
Yielding 2
2
Yielding 1
1
Yielding 0
0
特别是,它错过了打印3。为什么?
引用的问题没有回答这个问题,因为我没有问send 做了什么。它将值发送回函数。我要问的是为什么在我发出send(3) 之后,下一个产量应该是 3,而不是导致 for 循环打印 3。
【问题讨论】:
-
首先,它也错过了 4。其次,你认为
c.send(3)是做什么的? -
@alfasin 因为
c.send(3),它错过了4。关键是代码应该将n设置为3,然后在下一个循环中,产生3。但它没有被打印出来。为什么? -
在
if newv is not None:块中添加print('newv: {}'.format(newv)会更清晰
标签: python generator coroutine