最近看到这样一段代码 运行的结果是
5 2 1 0
有点不明白为什么3没有被print出来 我认为给出的结果应该是 53210
- # 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)
看了 关于send是这样说的 send给generator的value会成为当前yield的结果 并且send的返回结果是下一个yield的结果(或者引发StopIteration异常)也就是说此处s.send(3)会返回3 并且在第8行suspend for循环 调用generator的next函数 从第9行开始执行 此时当前yield的值为None 所以n -= 1 之后yield2 并且suspend在第8行
Resumes the execution and ``sends'' a value into the generator function. The value argument becomes the result of the current yieldexpression. The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. When send() is called to start the generator, it must be called with None as the argument, because there is no yield expression that could receieve the value.
阅读(5825) | 评论(0) | 转发(0) |