python yield生成器send发送数据问题,pythonyield,def countdow
python yield生成器send发送数据问题,pythonyield,def countdow
def countdown(n): print "conunting down form" ,n while n>=0: print "first n:",n newvalue=(yield n) print "second n:",n print "first newvalue",newvalue if newvalue is not None: n=newvalue else: n-=1 print "second newvalue",newvaluec=countdown(5)for n in c: # print n if n==5: c.send(3)
输出结果:
conunting down form 5
first n: 5
second n: 5
first newvalue 3
second newvalue 3
first n: 3
second n: 3
first newvalue None
second newvalue None
first n: 2
second n: 2
first newvalue None
second newvalue None
first n: 1
second n: 1
first newvalue None
second newvalue None
first n: 0
second n: 0
first newvalue None
second newvalue None
这个期间发送的send值是不是改变了n的值,是不是会继续进行n=3的迭代?
应该是send(3)作为(yield 5)的返回值,赋值给newvalue。所以操作完后newvalue==3,后续的n=newvalue导致n发生变化。
如果没有send操作,newvalue的值应该为None。send(3)作为(yield 5)的返回值,赋值给newvalue,所以n为3.从而导致后续的变化。值得注意的是yield n 会做为整个函数的返回值,而 newvalue = yield n,newvalue为None。
编橙之家文章,
相关内容
- 哪里有Python面试题库集合可以练习,python面试题库集合
- Django可以建立指向自己model的外键吗?,djangomodel,如题,
- python list合并数据内有符号怎么处理,pythonlist,现在遇到
- 想用python调用windows录音机保存文件需要怎么做,,pyth
- 求教关于支付宝与银行卡自动转帐设置及安全性的问题
- 请问tornado异步下redirect问题,tornadoredirect,我本想实现一
- 求python大牛帮看看ctypes.string_at的问题,,代码我也放在
- Python元类怎么理解更好吸收,python元类理解,如题,py
- 那些知名BBS是用python写的呢?,bbspython写,有哪些用pyth
- Python将文件中空格变成换行的方法如何做,python换行
评论关闭