4
我想生成的發送功能,我期待的是發送將變更此是屈服值,所以我在IPython的嘗試:python「send」方法不會改變「next」的值嗎?
In [17]: def z(n):
...: i=0
...: while(i<n):
...: val=yield i
...: print "value is:",val
...: i+=1
...:
In [24]: z1=z(10)
In [25]: z1.next()
Out[25]: 0
In [26]: z1.send(5) # I was expecting that after "send", output value will become "5"
value is: 5
Out[26]: 1
In [27]: z1.next()
value is: None # I was expecting that z1.next() will restart from "6" because I sent "5"
Out[27]: 2
嗯,我想我有什麼「派」錯誤的理解確實,如何改正它?
如果我只是使用z1.next(),它會打印數字;當使用「print z1.next()」時,出現「value is」語句。爲什麼? – Troskyvs
@Troskyvs更新了答案,希望能回答你的問題。 – niemmi
謝謝,我開始理解你的觀點,在發生器內部,「val = yield i」表示val從外部「發送」命令設置,而外部調用者從「yield i」獲取返回值。這很難理解爲什麼「next()」等於「send(None)」,因此val是「None」。 – Troskyvs