yield的使用
例一:斐波那契數列
例2:文件读取
def fib(max):
n,a,b = 0,0,1
while n<max:
print b
a,b = b,a+b
n +=1
def fib_list(max):
n,a,b = 0,0,1
list = []
while n<max:
list.append(b)
a,b = b,a+b
n +=1
return list
class Fib(object):
"""docstring for Fab"""
def __init__(self, max):
self.max = max
self.n,self.a,self.b = 0,0,1
def __iter__(self):
return self
def next(self):
if self.n < self.max:
r = self.b
self.a,self.b = self.b,self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()
def fib_final(max):
n,a,b = 0,0,1
while n<max:
yield b
a,b = b,a+b
n += 1
if __name__ == '__main__':
for n in fib_final(5):
print n
例2:文件读取
def read_file(fpath):
BLOCK_SIZE = 1024
with open(fpath,'rb') as f:
while True:
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return
if __name__ == '__main__':
for line in read_file('fib.py'):
print line