本文主要是介绍yield:生成器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
def count(n):
while n > 0:
yield n #生成值:n
n -= 1
if __name__ == '__main__':
c=count(2)
print c.next()
print c.next()
print c.next()
./iter.py
2
1
Traceback (most recent call last):
File "./iter.py", line 26, in <module>
print c.next()
StopIteration
###################################################3333
18 def count(n):
19 print 'counting'
20 while n > 0:
21 print 'n :%d'%n
22 print ' before yield'
23 yield n #生成值:n
24 n -= 1
25 print 'after yield'
26 if __name__ == '__main__':
27 c=count(2)
28 print 'call next'
29 print c.next()
30 print c.next()
"iter.py" 46L, 1073C written
common> ./iter.py
call next
counting
n :2
before yield
2
after yield
n :1
before yield
1
after yield
Traceback (most recent call last):
File "./iter.py", line 31, in <module>
print c.next()
StopIteration
在调用count函数时:c=count(5),并不会打印"counting"只有等到调用c.next()时才真正执行里面的语句。每次调用next()方法时,count函数会运行到语句yield n
处为止,next()的返回值就是生成值n
,再次调用next()方法时,函数继续执行yield之后的语句
for i in count(5):
print i,
这篇关于yield:生成器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!