Python3.x:生成器简介
概念
任何使用yield的函数都称之为生成器;使用yield,可以让函数生成一个序列,该函数返回的对象类型是"generator",通过该对象连续调用__next__()方法返回序列值;
实例
生成器函数只有在调用__next()__方法的时候才开始执行函数里面的语句,例如:
defcount(n):while n >0:yield n #生成值:n
n -= 1
使用yield,可以让函数生成一个序列,该函数返回的对象类型是"generator",通过该对象连续调用__next__()方法返回序列值;
c = count(5)
c.__next__() #python 3.4.3要使用c.__next__()不能使用c.next()
结果:5c.__next__()
结果4
在调用count函数时:c=count(5),并不会打印"counting"只有等到调用c.__next__()时才真正执行里面的语句。每次调用__next__()方法时,count函数会运行到语句yield n处为止,__next__()的返回值就是生成值n,再次调用__next__()方法时,函数继续执行yield之后的语句(熟悉Java的朋友肯定知道Thread.yield()方法,作用是暂停当前线程的运行,让其他线程执行),例如:
defcount(n):print ("cunting")while n >0:print ('before yield')yield n #生成值:n
n -= 1
print ('after yield' )
上述代码在第一次调用__next__方法时,并不会打印"after yield"。如果一直调用__next__方法,当执行到没有可迭代的值后,程序就会报错:
Traceback (most recent call last): File "", line 1, in StopIteratio
所以一般不会手动的调用__next__方法,而使用for循环:
for i in count(5):print (i)
实例:用yield实现斐波那契数列
deffibonacci():
a=b=1
yieldayieldbwhileTrue:
a,b= b,a+byield b
调用:
for num infibonacci():if num > 100:break
print (num),
yield中return的作用:
作为生成器,因为每次迭代就会返回一个值,所以不能显示的在生成器函数中return 某个值,包括None值也不行,否则会抛出“SyntaxError”的异常,但是在函数中可以出现单独的return,表示结束该语句。
通过固定长度的缓冲区不断读文件,防止一次性读取出现内存溢出的例子:
defread_file(path):
size= 1024with open(path,'r') as f:whileTrue:
block=f.read(SIZE)ifblock:yieldblockelse:return
如果是在函数中return 具体某个值,就直接抛异常:
deftest_return():yield 4
return0
结果:File"", line 3SyntaxError:'return' with argument inside generator