【11.5】生成器进阶--send、close和throw方法

1.send方法

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # 启动生成器有两种方法,next()和send()
 4 
 5 
 6 def gen_func():
 7     # 1.可以产出值   2.可以接收值(调用方传递的值)
 8     html = yield 'http://projectsedu.com'
 9     print(html)
10     yield 2
11     yield 3
12     return 'zy'
13 
14 
15 if __name__ == '__main__':
16     # 生成生成器对象
17     gen = gen_func()
18     # 在调用send发送非None值之前,我们必须启动一次生成器,方式有两种1.gen.send(None),2.next(gen)
19     url = gen.send(None)
20     # download html
21     html = 'zy'
22     # send()可以传递值进入生成器内部,同时重启生成器执行到下一个yield位置
23     print(gen.send(html))
24 
25     # print(next(gen))
26     # print(next(gen))
27     # print(next(gen))
zy
2

2.close方法

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 
 5 def gen_func():
 6     yield 'http://projectsedu.com'
 7     yield 2
 8     yield 3
 9     return 'zy'
10 
11 
12 if __name__ == '__main__':
13     # 生成生成器对象
14     gen = gen_func()
15     print(next(gen))
16     gen.close()
17     print(next(gen))
Traceback (most recent call last):
http://projectsedu.com
  File "C:/Users/Administrator/Python/imooc/Generator/generator_close.py", line 17, in <module>
    print(next(gen))
StopIteration

3.throw方法

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 
 5 def gen_func():
 6     try:
 7         yield 'http://projectsedu.com'
 8     except Exception as e:
 9         pass
10     yield 2
11     yield 3
12     return 'zy'
13 
14 
15 if __name__ == '__main__':
16     # 生成生成器对象
17     gen = gen_func()
18     print(next(gen))
19     # 在生成器暂停的地方抛出类型为 type 的异常,并返回下一个 yield 的返回值。
20     print(gen.throw(Exception, 'download error'))
21     print(next(gen))
http://projectsedu.com
2
3
原文地址:https://www.cnblogs.com/zydeboke/p/11341100.html