深刻理解yield

yield的英文單詞意思是生產,剛接觸Python的時候感到很是困惑,一直沒弄明白yield的用法。python

只是粗略的知道yield能夠用來爲一個函數返回值塞數據,好比下面的例子:bash

1
2
3
def  addlist(alist):
     for  in  alist:
         yield  +  1

取出alist的每一項,而後把i + 1塞進去。而後經過調用取出每一項:函數

1
2
3
alist  =  [ 1 2 3 4 ]
for  in  addlist(alist):
     print  x,

這的確是yield應用的一個例子學習

1. 包含yield的函數spa

假如你看到某個函數包含了yield,這意味着這個函數已是一個Generator,它的執行會和其餘普通的函數有不少不一樣。好比下面的簡單的函數:code

1
2
3
4
def  h():
     print  'To be brave'
     yield  5
h()

能夠看到,調用h()以後,print 語句並無執行!這就是yield,那麼,如何讓print 語句執行呢?這就是後面要討論的問題,經過後面的討論和學習,就會明白yield的工做原理了。ci

2. yield是一個表達式get

Python2.5之前,yield是一個語句,但如今2.5中,yield是一個表達式(Expression),好比:generator

m = yield 5string

表達式(yield 5)的返回值將賦值給m,因此,認爲 m = 5 是錯誤的。那麼如何獲取(yield 5)的返回值呢?須要用到後面要介紹的send(msg)方法。

3. 透過next()語句看原理

如今,咱們來揭曉yield的工做原理。咱們知道,咱們上面的h()被調用後並無執行,由於它有yield表達式,所以,咱們經過next()語句讓它執行。next()語句將恢復Generator執行,並直到下一個yield表達式處。好比:

1
2
3
4
5
6
def  h():
     print  'Wen Chuan'
     yield  5
     print  'Fighting!'
=  h()
c. next ()

c.next()調用後,h()開始執行,直到遇到yield 5,所以輸出結果:

Wen Chuan

當咱們再次調用c.next()時,會繼續執行,直到找到下一個yield表達式。因爲後面沒有yield了,所以會拋出異常:

1
2
3
4
5
6
Wen Chuan
Fighting!
Traceback (most recent call last):
   File  "/home/evergreen/Codes/yidld.py" , line  11 in  <module>
     c. next ()
StopIteration

4. send(msg) 與 next()

瞭解了next()如何讓包含yield的函數執行後,咱們再來看另一個很是重要的函數send(msg)。其實next()和send()在必定意義上做用是類似的,區別是send()能夠傳遞yield表達式的值進去,而next()不能傳遞特定的值,只能傳遞None進去。所以,咱們能夠看作

c.next() 和 c.send(None) 做用是同樣的。

來看這個例子:

1
2
3
4
5
6
7
8
9
def  h():
     print  'Wen Chuan' ,
     =  yield  5   # Fighting!
     print  m
     =  yield  12
     print  'We are together!'
=  h()
c. next ()   #至關於c.send(None)
c.send( 'Fighting!' )   #(yield 5)表達式被賦予了'Fighting!'

輸出的結果爲:

Wen Chuan Fighting!

須要提醒的是,第一次調用時,請使用next()語句或是send(None),不能使用send發送一個非None的值,不然會出錯的,由於沒有yield語句來接收這個值。

5. send(msg) 與 next()的返回值

send(msg) 和 next()是有返回值的,它們的返回值很特殊,返回的是下一個yield表達式的參數。好比yield 5,則返回 5 。到這裏,是否是明白了一些什麼東西?本文第一個例子中,經過for i in alist 遍歷 Generator,實際上是每次都調用了alist.Next(),而每次alist.Next()的返回值正是yield的參數,即咱們開始認爲被壓進去的東東。咱們再延續上面的例子:

1
2
3
4
5
6
7
8
9
10
def  h():
     print  'Wen Chuan' ,
     =  yield  5   # Fighting!
     print  m
     =  yield  12
     print  'We are together!'
=  h()
=  c. next ()   #m 獲取了yield 5 的參數值 5
=  c.send( 'Fighting!' )   #d 獲取了yield 12 的參數值12
print  'We will never forget the date' , m,  '.' , d

輸出結果:

1
2
Wen Chuan Fighting!
We will never forget the  date  5 . 12

6. throw() 與 close()中斷 Generator

中斷Generator是一個很是靈活的技巧,能夠經過throw拋出一個GeneratorExit異常來終止Generator。Close()方法做用是同樣的,其實內部它是調用了throw(GeneratorExit)的。咱們看:

1
2
3
4
5
6
7
8
def  close( self ):
     try :
         self .throw(GeneratorExit)
     except  (GeneratorExit, StopIteration):
         pass
     else :
         raise  RuntimeError( "generator ignored GeneratorExit" )
# Other exceptions are not caught

所以,當咱們調用了close()方法後,再調用next()或是send(msg)的話會拋出一個異常:

1
2
3
4
Traceback (most recent call last):
   File  "/home/evergreen/Codes/yidld.py" , line 14,  in  <module>
     d = c.send( 'Fighting!' )   #d 獲取了yield 12 的參數值12
StopIteration
相關文章
相關標籤/搜索