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,

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值