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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值