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