python yield send 一个容易犯错的地方

python yield send 一个容易犯错的地方 2012-10-29 12:23:55

分类: Python/Ruby

http://blog.chinaunix.net/uid-11989741-id-3389226.html

最近看到这样一段代码  运行的结果是
5 2 1 0

有点不明白为什么3没有被print出来  我认为给出的结果应该是 53210

点击(此处)折叠或打开

  1. # bogus.py
  2. #
  3. # Bogus example of a generator that produces and receives values

  4. def countdown(n):
  5.     print "Counting down from", n
  6.     while n >= 0:
  7.         newvalue = (yield n)
  8.         # If a new value got sent in, reset n with it
  9.         if newvalue is not None:
  10.             n = newvalue
  11.         else:
  12.             n -= 1

  13. # The holy grail countdown
  14. c = countdown(5)
  15. for x in c:
  16.     print x
  17.     if x == 5:
  18.         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)
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.

你可能感兴趣的:(python yield send 一个容易犯错的地方)