#!/usr/bin/env python#coding=utf-8class Fib:def __init__(self):self.a,self.b = 0,1def next(self):self.a,self.b = self.b,self.a+self.breturn self.adef __iter__(self):return selffibs = Fib()for f in fibs:if f < 10000:print felse:break
#!/usr/bin/env python#coding=utf-8def fib():a,b = 0,1while 1:a,b = b,a+byield afor f in fib():if f < 10000:print felse:break生成器接收参数实例:def counter(start_at):count = start_atwhile True:print ‘before count %s‘ % countval = (yield count)print ‘after count %s, val %s‘ % (count, val)if val is not None:count = valprint ‘sts a‘else:count += 1print ‘sts b‘if __name__ == ‘__main__‘:count = counter(5)print ‘calling1 count.next():‘, count.next()print ‘calling2 count.next():‘, count.next()print ‘calling3 count.next():‘, count.next()print ‘calling4 count.next():‘, count.next()print ‘calling5 count.next():‘, count.next()print ‘-------start---------‘s = count.send(20)print ‘s‘, sprint ‘calling count.next():‘, count.next()print ‘calling count.close():‘, count.close()print ‘calling count.next():‘, count.next()
结果:calling1 count.next(): before count 55calling2 count.next(): after count 5, val Nonests bbefore count 66calling3 count.next(): after count 6, val Nonests bbefore count 77calling4 count.next(): after count 7, val Nonests bbefore count 88calling5 count.next(): after count 8, val Nonests bbefore count 99-------start---------after count 9, val 20sts abefore count 20s 20calling count.next(): after count 20, val Nonests bbefore count 2121calling count.close(): Nonecalling count.next():Traceback (most recent call last):File "D:\Python27\counter.py", line 26, in <module>print ‘calling count.next():‘, count.next()StopIteration
迭代器就是重复地做一些事情,可以简单的理解为循环,在python中实现了__iter__方法的对象是可迭代的,实现了next()方法的对象是迭代器,这样说起来有
原文:http://www.cnblogs.com/highroom/p/f7a6f4237f5f5501c834b261f7a4c2f0.html