5. Python3 中的生成器的高級方法 及總結

回顧:

  • 生成器就是含有yield操作的函數,生成器函數的返回值就是一個迭代器(generator object)

主要內容:

  • 外部如何給生成器發送一個值,臨時按需變化迭代生成值。(send方法)
  • 生成器返回的迭代器,一般只能使用一次。可采用內在的異常機制對第二次調用報錯。
  • 生成器“對象”(生成器產生的迭代器對象)的close方法示例
  • 個人理解與總結

5.1 send 函數

  • 錯誤的例子
>>> def simpleGen(value): # 定義了一個簡單的生成器
...     while True:
...         yield value
... 
>>> gen = simpleGen(42);
>>> print(gen.__next__(),gen.__next__())
42 42
>>> gen.send(10);
42
>>> print(gen.__next__(),gen.__next__())
42 42

yield 此處是一個語句。然而我們需要在生成器函數中對gen.send(10);進行響應,那么我們就要使用yield 表達式, yield 不再是語句,而是表達式?。?!

  • 正確的例子
#正確的例子
>>> def simpleGen(value):
...     new = None;
...     i = 0;
...     while True:
...         i +=1
...         print('In Func (before):',i, new, value)
...         new = yield value
...         print('In Func (after):',i, new, value)
...         value = new;
... 
>>> gen = simpleGen(42); # nothing happend 
>>> print(gen.__next__()) # called 1st, get 42
In Func (before): 1 None 42
42
>>> print(gen.__next__()) # called 2nd, get None, this is important!
In Func (after): 1 None 42
In Func (before): 2 None None
None
>>> print(gen.send(10));    # called 3rd, get what you set
In Func (after): 2 10 None
In Func (before): 3 10 10
10
>>> print(gen.__next__()) # called 4th, get None, this is important!
In Func (after): 3 None 10
In Func (before): 4 None None
None

此處應該有結論:

  1. 構造函數啥都不干,除了賦值
  2. send函數和__next__函數一樣,都喚醒了沉睡中的yield表達式
  3. yield表達式的值在正常情況下是None
  • 最終更佳的例子(處理None)
>>> def simpleGen(value):
...     while True:
...         new = yield value
...         if new is not None:
...              value = new;
... 
>>> gen = simpleGen(42); # nothing happend 
>>> print(gen.__next__()) # called 1st, get 42
42
>>> print(gen.__next__()) # called 2nd, get 42
42
>>> print(gen.send(10));    # called 3rd, get what you set
10
>>> print(gen.__next__()) # called 4th, also get what you set
10

5.2 throw 方法

這個很簡單,就是通過語句,然生成器內部產生異常,注意異常報出的位置(yield 語句)

>>> def simpleGen(value):
...     while True:
...         new = yield value
...         if new is not None:
...              value = new;
... 
>>> gen = simpleGen(42); # nothing happend 
>>> print(gen.__next__()) # called 1st, get 42
42
>>> gen.throw(StopIteration)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in simpleGen ## 注意異常報出的位置(yield 語句)。
StopIteration

5.3 close 語句

顯然 throw方法產生的異常并沒有在內部處理掉,直接立馬傳遞到上一層了。我們能否設置下迭代生成器的終止,也就是不能產生下一個了。那就是無參數的close方法。

>>> def simpleGen(value):
...     while True:
...         new = yield value
...         if new is not None:
...              value = new;
... 
>>> gen = simpleGen(42); # nothing happend 
>>> print(gen.__next__()) # called 1st, get 42
42
>>> gen.close() # 終止了這個迭代器,但是沒有異常
>>> print(gen.__next__())  # 繼續取值,便產生了StopIteration的異常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

5.4 小結下:

學習迭代器和生成器有一兩天了,自己也編程實現了大部分的功能。其目的都是為了高效的迭代循環而生的。那么循環的處理方式有如下幾種:

  • 直接采用元組、列表、字符串
  • 利用內置的迭代器(xrange函數等)
  • 自己構造類(迭代器)(__next__,__iter__)
  • 使用yield函數(生成器)(yield,__next__,send, throw, close)

感受,在表達形式上,Python確實和c、c++語言有較大差別。但是,這種迭代器的核心思想在C、C++中是以指針、引用等復雜的方式實現的,Python肯定是犧牲了一定的計算效率將其封裝成為了迭代器和生成器,帶來的好處是指針和內存的安全,編程效率的提升,所以python是一門很好的科學計算語言,使得開發者能夠注重算法層面的開發,而不是指針內存等煩人細節。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容