Pyhton generators and the yield keyword
At a glance,the yield statement is used to define generators,repalcing the return of a function to provide a result to its caller without destorying local variables.Unlike a function,where on each call it starts with new set of variables,a generator will resume the execution where it was left off.
被yield修饰的函数,会被python解释器当作generator
示例代码:
def countdown(): i=5 while i>0: yield i i-=1 for i in countdown(): print(i) print('********************') def gen(n):#斐波那契数列 i=0 pref=1#s[n-2] pres=2#s[n-1] cur=0#s[n] while i<n: if i<2: yield 1 else: cur=pref+pres yield cur pref=pres pres=cur i=i+1 if __name__=='__main__': for item in gen(20): print(item)
输出:
调用gen函数不会执行gen函数,它返回一个迭代器对象,第二次迭代时从yield x的下一条语句开始执行,再到下一次遇到yield。
虽然执行流程按照函数的流程执行,但是每次执行到yield时就会中断,它使一个函数获得了迭代能力。