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,