Python生成器

yield生成器:

  通过使用yield,可以让函数生成一个序列,函数的返回对象为"generator",通过对对象连续调用next()来返回序列的值

生成器函数只有在调用next()方法的时候才开始执行函数里面的语句

Python代码  收藏代码
  1. def count(n):  
  2.     print "cunting"  
  3.     while n > 0:  
  4.         yield n   #生成值:n  
  5.         n -= 1  

在调用count函数时:c=count(5),并不会打印"counting"只有等到调用c.next()时才真正执行里面的语句。每次调用next()方法时,count函数会运行到语句yield n处为止,next()的返回值就是生成值n,再次调用next()方法时,函数继续执行yield之后的语句(熟悉Java的朋友肯定知道Thread.yield()方法,作用是暂停当前线程的运行,让其他线程执行),如:

Python代码  收藏代码
  1. def count(n):  
  2.     print "cunting"  
  3.     while n > 0:  
  4.         print 'before yield'  
  5.         yield n   #生成值:n  
  6.         n -= 1  
  7.         print 'after yield'  

上述代码在第一次调用next方法时,并不会打印"after yield"。如果一直调用next方法,当执行到没有可迭代的值后,程序就会报错:

Traceback (most recent call last): File "", line 1, in StopIteration

所以一般不会手动的调用next方法,而使用for循环:

Python代码  收藏代码
  1. for i in count(5):  
  2.     print i,  
腾飞前的蛰伏
原文地址:https://www.cnblogs.com/xiaoli2018/p/4411195.html