首页 > 编程语言 > 详细

python生成器

时间:2015-03-16 20:58:17      阅读:303      评论:0      收藏:0      [点我收藏+]

什么是 python 式的生成器?从句法上讲,生成器是一个带 yield 语句的函数。一个函数或者子
程序只返回一次,但一个生成器能暂停执行并返回一个中间的结果----那就是 yield 语句的功能,返
回一个值给调用者并暂停执行。当生成器的 next()方法被调用的时候,它会准确地从离开地方继续
(当它返回[一个值以及]控制给调用者时)

简单实例

  1. def gen():
  2. yield 1
  3. yield 2
  4. yield 3
  5. f = gen()
  6. print f.next()
  7. print f.next()
  8. print f.next()

输出结果

  1. 1
  2. 2
  3. 3

从结果我们可以看出每次调用函数对象的next方法时,总是从上次离开的地方继续执行的.

加强的生成器

在 python2.5 中,一些加强特性加入到生成器中,所以除了 next()来获得下个生成的值,用户
可以将值回送给生成器[send()],在生成器中抛出异常,以及要求生成器退出[close()]

  1. def gen(x):
  2. count = x
  3. while True:
  4. val = (yield count)
  5. if val is not None:
  6. count = val
  7. else:
  8. count += 1
  9. f = gen(5)
  10. print f.next()
  11. print f.next()
  12. print f.next()
  13. print ‘====================‘
  14. print f.send(9)#发送数字9给生成器
  15. print f.next()
  16. print f.next()

输出

  1. 5
  2. 6
  3. 7
  4. ====================
  5. 9
  6. 10
  7. 11




python生成器

原文:http://www.cnblogs.com/csu_xajy/p/4342729.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!