生成器不會把結果保存在一個系列中,而是保存生成器的狀態,在每次進行迭代時返回一個值,直到遇到StopIteration異常結束。html
>>> gen = (x**2 for x in range(5)) >>> gen <generator object <genexpr> at 0x0000000002FB7B40> >>> for g in gen: ... print(g, end='-') ... 0-1-4-9-16- >>> for x in [0,1,2,3,4,5]: ... print(x, end='-') ... 0-1-2-3-4-5-
下面爲一個能夠無窮生產奇數的生成器函數。python
def odd(): n=1 while True: yield n n+=2 odd_num = odd() count = 0 for o in odd_num: if count >=5: break print(o) count +=1
固然經過手動編寫迭代器能夠實現相似的效果,只不過生成器更加直觀易懂ide
class Iter: def __init__(self): self.start=-1 def __iter__(self): return self def __next__(self): self.start +=2 return self.start I = Iter() for count in range(5): print(next(I))
題外話: 生成器是包含有__iter__()和__next__()方法的,因此能夠直接使用for來迭代,而沒有包含StopIteration的自編Iter來只能經過手動循環來迭代。函數
>>> from collections import Iterable >>> from collections import Iterator >>> isinstance(odd_num, Iterable) True >>> isinstance(odd_num, Iterator) True >>> iter(odd_num) is odd_num True >>> help(odd_num) Help on generator object: odd = class generator(object) | Methods defined here: | | __iter__(self, /) | Implement iter(self). | | __next__(self, /) | Implement next(self). ......
看到上面的結果,如今你能夠頗有信心的按照Iterator的方式進行循環了吧!code
在 for 循環執行時,每次循環都會執行 fab 函數內部的代碼,執行到 yield b 時,fab 函數就返回一個迭代值,下次迭代時,代碼從 yield b 的下一條語句繼續執行,而函數的本地變量看起來和上次中斷執行前是徹底同樣的,因而函數繼續執行,直到再次遇到 yield。看起來就好像一個函數在正常執行的過程當中被 yield 中斷了數次,每次中斷都會經過 yield 返回當前的迭代值。orm
>>> def g1(): ... yield 1 ... >>> g=g1() >>> next(g) #第一次調用next(g)時,會在執行完yield語句後掛起,因此此時程序並無執行結束。 1 >>> next(g) #程序試圖從yield語句的下一條語句開始執行,發現已經到告終尾,因此拋出StopIteration異常。 Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
>>> def g2(): ... yield 'a' ... return ... yield 'b' ... >>> g=g2() >>> next(g) #程序停留在執行完yield 'a'語句後的位置。 'a' >>> next(g) #程序發現下一條語句是return,因此拋出StopIteration異常,這樣yield 'b'語句永遠也不會執行。 Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
生成器沒有辦法使用return來返回值。協程
>>> def g3(): ... yield 'hello' ... return 'world' ... >>> g=g3() >>> next(g) 'hello' >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration: world
>>> help(odd_num) Help on generator object: odd = class generator(object) | Methods defined here: ...... | close(...) | close() -> raise GeneratorExit inside generator. | | send(...) | send(arg) -> send 'arg' into generator, | return next yielded value or raise StopIteration. | | throw(...) | throw(typ[,val[,tb]]) -> raise exception in generator, | return next yielded value or raise StopIteration. ......
手動關閉生成器函數,後面的調用會直接返回StopIteration異常。htm
>>> def g4(): ... yield 1 ... yield 2 ... yield 3 ... >>> g=g4() >>> next(g) 1 >>> g.close() >>> next(g) #關閉後,yield 2和yield 3語句將再也不起做用 Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
生成器函數最大的特色是能夠接受外部傳入的一個變量,並根據變量內容計算結果後返回。
這是生成器函數最難理解的地方,也是最重要的地方,實現後面我會講到的協程就全靠它了。blog
def gen(): value=0 while True: receive=yield value if receive=='e': break value = 'got: %s' % receive g=gen() print(g.send(None)) print(g.send('aaa')) print(g.send(3)) print(g.send('e'))
執行流程:內存
0 got: aaa got: 3 Traceback (most recent call last): File "h.py", line 14, in <module> print(g.send('e')) StopIteration
用來向生成器函數送入一個異常,能夠結束系統定義的異常,或者自定義的異常。
throw()後直接跑出異常並結束程序,或者消耗掉一個yield,或者在沒有下一個yield的時候直接進行到程序的結尾。
def gen(): while True: try: yield 'normal value' yield 'normal value 2' print('here') except ValueError: print('we got ValueError here') except TypeError: break g=gen() print(next(g)) print(g.throw(ValueError)) print(next(g)) print(g.throw(TypeError))
輸出結果爲:
normal value we got ValueError here normal value normal value 2 Traceback (most recent call last): File "h.py", line 15, in <module> print(g.throw(TypeError)) StopIteration
解釋:
下面給出一個綜合例子,用來把一個多維列表展開,或者說扁平化多維列表)
def flatten(nested): try: #若是是字符串,那麼手動拋出TypeError。 if isinstance(nested, str): raise TypeError for sublist in nested: #yield flatten(sublist) for element in flatten(sublist): #yield element print('got:', element) except TypeError: #print('here') yield nested L=['aaadf',[1,2,3],2,4,[5,[6,[8,[9]],'ddf'],7]] for num in flatten(L): print(num)
若是理解起來有點困難,那麼把print語句的註釋打開在進行查看就比較明瞭了。
yield產生的函數就是一個迭代器,因此咱們一般會把它放在循環語句中進行輸出結果。
有時候咱們須要把這個yield產生的迭代器放在另外一個生成器函數中,也就是生成器嵌套。
好比下面的例子:
def inner(): for i in range(10): yield i def outer(): g_inner=inner() #這是一個生成器 while True: res = g_inner.send(None) yield res g_outer=outer() while True: try: print(g_outer.send(None)) except StopIteration: break
此時,咱們能夠採用yield from語句來減小我麼你的工做量。
def outer2(): yield from inner()
固然 ,yield from語句的重點是幫咱們自動處理內外層之間的異常問題,這裏有2篇寫的很好的文章,因此我就再也不囉嗦了。
http://blog.theerrorlog.com/yield-from-in-python-3.html
http://stackoverflow.com/questions/9708902/in-practice-what-are-the-main-uses-for-the-new-yield-from-syntax-in-python-3
說明: