#!/usr/bin/env python
#coding=utf-8
class Fib:
def __init__(self):
self.a,self.b = 0,1
def next(self):
self.a,self.b = self.b,self.a+self.b
return self.a
def __iter__(self):
return self
fibs = Fib()
for f in fibs:
if f < 10000:
print f
else:
break
#!/usr/bin/env python
#coding=utf-8
def fib():
a,b = 0,1
while 1:
a,b = b,a+b
yield a
for f in fib():
if f < 10000:
print f
else:
break
生成器接收参数实例:
def counter(start_at):
count = start_at
while True:
print ‘before count %s‘ % count
val = (yield count)
print ‘after count %s, val %s‘ % (count, val)
if val is not None:
count = val
print ‘sts a‘
else:
count += 1
print ‘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‘, s
print ‘calling count.next():‘, count.next()
print ‘calling count.close():‘, count.close()
print ‘calling count.next():‘, count.next()
结果:
calling1 count.next(): before count 5
5
calling2 count.next(): after count 5, val None
sts b
before count 6
6
calling3 count.next(): after count 6, val None
sts b
before count 7
7
calling4 count.next(): after count 7, val None
sts b
before count 8
8
calling5 count.next(): after count 8, val None
sts b
before count 9
9
-------start---------
after count 9, val 20
sts a
before count 20
s 20
calling count.next(): after count 20, val None
sts b
before count 21
21
calling count.close(): None
calling 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