PTT
Submit
Submit
选择语言
正體中文
简体中文
PTT
Python
[问题] 请问generator的send方法
楼主:
Tomcat
(我想我疯了)
2018-01-19 19:23:42
小弟正在学习PYTHON,看到generator时,下面这支是看得懂...
gen.send.preparation.stop.py
stop = False
def counter(start=0):
n = start
while not stop:
yield n
n += 1
c = counter()
print(next(c)) # prints: 0
print(next(c)) # prints: 1
stop = True
print(next(c)) # raises StopIteration
不过到了下面这支后就卡关了...
我卡关的点在于... 为什么执行# C步骤时,只有印出0;
而执行# D时却是印出:
<class 'str'> Wow!
1
为什么不是先印出1呢? 明明result = yield n 就是在前面啊...
如果按照这逻辑的话,步骤# F应该也要先印出3才对...
可是却先执行# B 印出<class 'str'> Q 后产生StopIteration
麻烦各位大大赐教了,感谢!!
gen.send.py
def counter(start=0):
n = start
while True:
result = yield n # A
print(type(result), result) # B
if result == 'Q':
break
n += 1
c = counter()
print(next(c)) # C
print(c.send('Wow!')) # D
print(next(c)) # E
print(c.send('Q')) # F
执行结果:
$ python gen.send.py
0
<class 'str'> Wow!
1
<class 'NoneType'> None
2
<class 'str'> Q
Traceback (most recent call last):
File "gen.send.py", line 14, in <module>
print(c.send('Q')) # F
StopIteration
作者:
seLain
(建筑的永恒之道)
2018-01-19 20:23:00
C->A->C(0)->D->A->B(Wow)->A->D(1)->....another example:
https://goo.gl/5VVhSZ
作者:
zerof
(猫橘毛发呆雕像)
2018-01-19 22:34:00
next(g) == g.send(None)yield 右边的值会先出来,左值会在下次 send 的时候 assign& 这个其实是 coroutine 了,见 PEP342
继续阅读
[情报] 线上8小时爬虫课程/64折倒数3天
va12024
Re: [问题] 判断布林值的问题
MOONY135
[问题] Windows重导向stdout至档案发生编码错误
danny0838
[问题] 把django deploy 到 apache
redbxh
[问题] 新手请益,做seo相关资料蒐集
yuimei
[问题] 判断布林值的问题
zuso
[讨论] DataCamp征求共用会员
maybe0930
[问题] Tk Filedialog 存盘如何存成有副档名?
caesar0929
[问题] matplotlib 画饼图时值0能否去除?
qwerfvcxz32
[问题] 如何呼叫c++函式并传入、回传numpy array
hardman1110
Links
booklink
Contact Us: admin [ a t ] ucptt.com