生成器不会把结果保存在一个系列中,而是保存生成器的状态,在每次进行迭代时返回一个值,直到遇到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
说明: