标签:
什么是 python 式的生成器?从句法上讲,生成器是一个带 yield 语句的函数。一个函数或者子
程序只返回一次,但一个生成器能暂停执行并返回一个中间的结果----那就是 yield 语句的功能,返
回一个值给调用者并暂停执行。当生成器的 next()方法被调用的时候,它会准确地从离开地方继续
(当它返回[一个值以及]控制给调用者时)
def gen():yield 1yield 2yield 3f = gen()print f.next()print f.next()print f.next()
输出结果
123
从结果我们可以看出每次调用函数对象的next方法时,总是从上次离开的地方继续执行的.
在 python2.5 中,一些加强特性加入到生成器中,所以除了 next()来获得下个生成的值,用户
可以将值回送给生成器[send()],在生成器中抛出异常,以及要求生成器退出[close()]
def gen(x):count = xwhile True:val = (yield count)if val is not None:count = valelse:count += 1f = gen(5)print f.next()print f.next()print f.next()print ‘====================‘print f.send(9)#发送数字9给生成器print f.next()print f.next()
输出
567====================91011
标签:
原文地址:http://www.cnblogs.com/csu_xajy/p/4342729.html