生成器對象是一個迭代器。但是它比迭代器對象多了一些方法,它們包括send方法,throw方法和close方法。這些方法,主要是用于外部與生成器對象的交互。本文先介紹send方法。
send方法有一個參數,該參數指定的是上一次被掛起的yield語句的返回值。這樣說起來比較抽象,看下面的例子。
def MyGenerator(): value = (yield 1) value = (yield value)gen = MyGenerator()PRint gen.next()print gen.send(2)print gen.send(3)輸出的結果如下
12Traceback (most recent call last): File "test.py", line 18, in <module> print gen.send(3)StopIteration上面代碼的運行過程如下。當調用gen.next()方法時,python首先會執行MyGenerator方法的yield 1語句。由于是一個yield語句,因此方法的執行過程被掛起,而next方法返回值為yield關鍵字后面表達式的值,即為1。
當調用gen.send(2)方法時,python首先恢復MyGenerator方法的運行環境。同時,將表達式(yield 1)的返回值定義為send方法參數的值,即為2。這樣,接下來value=(yield 1)這一賦值語句會將value的值置為2。繼續運行會遇到yield value語句。因此,MyGenerator方法再次被掛起。同時,send方法的返回值為yield關鍵字后面表達式的值,也即value的值,為2。
當調用send(3)方法時MyGenerator方法的運行環境。同時,將表達式(yield value)的返回值定義為send方法參數的值,即為3。這樣,接下來value=(yield value)這一賦值語句會將value的值置為3。繼續運行,MyGenerator方法執行完畢,故而拋出StopIteration異常。
總的來說,send方法和next方法唯一的區別是在執行send方法會首先把上一次掛起的yield語句的返回值通過參數設定,從而實現與生成器方法的交互。但是需要注意,在一個生成器對象沒有執行next方法之前,由于沒有yield語句被掛起,所以執行send方法會報錯。例如
gen = MyGenerator()print gen.send(2)上面代碼的輸出為Traceback (most recent call last): File "test.py", line 16, in <module> print gen.send(2)TypeError: can't send non-None value to a just-started generator當然,下面的代碼是可以接受的gen = MyGenerator()print gen.send(None)因為當send方法的參數為None時,它與next方法完全等價。但是注意,雖然上面的代碼可以接受,但是不規范。所以,在調用send方法之前,還是先調用一次next方法為好。
新聞熱點
疑難解答