fab函数Python python fact函数( 三 )


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.
......
close()
手动关闭生成器函数 , 后面的调用会直接返回StopIteration异常 。
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
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()
生成器函数最大的特点是可以接受外部传入的一个变量 , 并根据变量内容计算结果后返回 。
这是生成器函数最难理解的地方,也是最重要的地方,实现后面fab函数Python我会讲到的协程就全靠它了 。
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
def gen():
value=https://www.04ip.com/post/0
while True:
receive=yield value
if receive=='e':
break
value = 'https://www.04ip.com/post/got: %s' % receive
g=gen()
print(g.send(None))
print(g.send('aaa'))
print(g.send(3))
print(g.send('e'))
执行流程:
通过g.send(None)或者next(g)可以启动生成器函数,并执行到第一个yield语句结束的位置 。此时,执行完了yield语句 , 但是没有给receive赋值 。yield value会输出初始值0注意:在启动生成器函数时只能send(None),如果试图输入其它的值都会得到错误提示信息 。
通过g.send(‘aaa’),会传入aaa,并赋值给receive , 然后计算出value的值,并回到while头部,执行yield value语句有停止 。此时yield value会输出”got: aaa”,然后挂起 。
通过g.send(3),会重复第2步,最后输出结果为”got: 3″
当我们g.send(‘e’)时,程序会执行break然后推出循环,最后整个函数执行完毕,所以会得到StopIteration异常 。
最后的执行结果如下:
Python
1
2
3
4
5
6
7
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的时候直接进行到程序的结尾 。
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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))
输出结果为:
Python
1
2
3
4
5
6
7
8
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
解释:
print(next(g)):会输出normal value,并停留在yield ‘normal value 2’之前 。

推荐阅读