2013-07-13 43 views
0
def h(): 
    print 'Wen Chuan', 
    m = yield 5 # Fighting! 
    print m 
    d = yield 12 
    print 'We are together!' 
c = h() 
m = c.next() #m gets the value of yield 5 
d = c.send('Fighting!') #d gets the value of yield 12 
print 'We will never forget the date', m, '.', d 

請檢查以上代碼。 它的運行結果低於:爲什麼產量回報值以這種方式改變?

>>> ================================ RESTART ================================ 
>>> 
Wen Chuan Fighting! 
We will never forget the date 5 . 12 

而且根據我的理解,第一產返回值更改爲「Fighting!」已經,但爲什麼以後當print m它仍然顯示值5?

回答

2

不,你沒有改變yield 5表達式使發生器產生什麼。

.send()將改變在什麼地方mh()將被設置爲只。

會發生什麼事是:

  • 創建h(),發電機的功能,並且執行被凍結。
  • 您在發電機上撥打.next()。執行被恢復,'Wen Chuan'被打印並且代碼運行直到yield 5表達式。 5被返回並分配給全球m。發電機再次暫停。
  • 您致電c.send('Fighting!')。執行被恢復,'Fighting!'被分配給生成器函數中的局部變量mprint m打印那個。執行yield 12,發生器暫停,12被分配給全局變量d
  • 'We will never forget the date', 5, '.', 12被打印。

至此發電機功能仍然暫停,和發電機功能的最後一行永遠不會執行。如果您再次打電話.next(),則會打印'We are together!',發電機端和StopIteration會被擡起。

1

m裏面和外面的功能是不相互影響的不同變量。

相關問題