python-基础-yeild和生成器

python中的yield

迭代器iterator

python中for循环可以用于可迭代的对象,迭代器实现了迭代协议的对象,即有next方法的对象会前进到下一个结果;
末尾是StopIteration
读文件的readlines(),文件会全部加载到内存中

for line in open("test.txt").readlines():
    print line

使用迭代器

for line in open("test.txt"):   #use file iterators
    print line

生成器constructor

包含yield语句的函数被编译成生成器
当函数被调用时,返回一个生成器对象,这个对象支持迭代器接口,函数包含的return用来返回yeild值;
生成器函数在生成值后会自动挂起并暂停他们的执行和状态,他的本地变量将保存状态信息,这些信息在函数恢复时将再度有效;

>>> def g(n):
...     for i in range(n):
...             yield i **2
...
>>> for i in g(5):
...     print i,":",
...
0 : 1 : 4 : 9 : 16 :

用Next方法看下

>>> t = g(5)
>>> t.next()
0
>>> t.next()
1
>>> t.next()
4
>>> t.next()
9
>>> t.next()
16
>>> t.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

在运行完5次next之后,生成器抛出了一个StopIteration异常,迭代终止。
再来看一个yield的例子,用生成器生成一个Fibonacci数列:

def fab(max):
    a,b = 0,1
    while a < max:
        yield a
        a, b = b, a+b
 
>>> for i in fab(20):
...     print i,",",
...
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 ,

yield 与 return

yield处返回一个值
如果没有return,返回StopIteration

>>> 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
>>>

如果遇到return直接抛出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

reuturn后返回的值是StopIteration异常的说明

生成器的方法

close()
send()
throw()
close
手动关闭生成器函数,后面的调用会直接返回StopIteration异常。

>>> 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

send()
生成器函数最大的特点是可以接受外部传入的一个变量,并根据变量内容计算结果后返回。

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'))

执行流程

执行流程:
1. 通过g.send(None)或者next(g)可以启动生成器函数,并执行到第一个yield语句结束的位置。此时,执行完了yield语句,但是没有给receive赋值。yield value会输出初始值0注意:在启动生成器函数时只能send(None),如果试图输入其它的值都会得到错误提示信息。
2. 通过g.send(‘aaa’),会传入aaa,并赋值给receive,然后计算出value的值,并回到while头部,执行yield value语句有停止。此时yield value会输出”got: aaa”,然后挂起。
3. 通过g.send(3),会重复第2步,最后输出结果为”got: 3″
当我们g.send(‘e’)时,程序会执行break然后推出循环,最后整个函数执行完毕,所以会得到StopIteration异常。

执行结果如下

0
got: aaa
got: 3
Traceback (most recent call last):
File "h.py", line 14, in <module>
  print(g.send('e'))
StopIteration

throw()
用来向生成器函数送入一个异常,可以结束系统定义的异常,或者自定义的异常。
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))

输出结果为:

解释:
1. print(next(g)):会输出normal value,并停留在yield ‘normal value 2’之前。
2. 由于执行了g.throw(ValueError),所以会跳过所有后续的try语句,也就是说yield ‘normal value 2’不会被执行,然后进入到except语句,打印出we got ValueError here。然后再次进入到while语句部分,消耗一个yield,所以会输出normal value。
3. print(next(g)),会执行yield ‘normal value 2’语句,并停留在执行完该语句后的位置。
4. g.throw(TypeError):会跳出try语句,从而print(‘here’)不会被执行,然后执行break语句,跳出while循环,然后到达程序结尾,所以跑出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)

总结

1. 按照鸭子模型理论,生成器就是一种迭代器,可以使用for进行迭代。
2. 第一次执行next(generator)时,会执行完yield语句后程序进行挂起,所有的参数和状态会进行保存。再一次执行next(generator)时,会从挂起的状态开始往后执行。在遇到程序的结尾或者遇到StopIteration时,循环结束。
3. 可以通过generator.send(arg)来传入参数,这是协程模型。
4. 可以通过generator.throw(exception)来传入一个异常。throw语句会消耗掉一个yield。可以通过generator.close()来手动关闭生成器。
5. next()等价于send(None)

参考

http://python.jobbole.com/81911/

posted @ 2017-02-09 19:44  zhangshihai1232  阅读(171)  评论(0)    收藏  举报