python yield send 一个容易犯错的地方
2012-10-29 12:23:55
分类: Python/Ruby
http://blog.chinaunix.net/uid-11989741-id-3389226.html
最近看到这样一段代码 运行的结果是
Resumes the execution and ``sends'' a value into the generator function. The
value argument becomes the result of the current yield expression.
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.
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的返回结果是下一个(即先对newvalue赋值,而yield的返回值则在下一个循环,本次执行赋值,而下一次的yield的值在返回给调用者)yield的结果(或者引发StopIteration异常)也就是说此处s.send(3)会返回3 并且在第8行suspend for循环 调用generator的next函数 从第9行开始执行 此时当前yield的值为None 所以n -= 1 之后yield2 并且suspend在第8行
send( | value) |