python的with是如何工作的
来源:互联网 发布:淘宝网床上四件套纯棉 编辑:程序博客网 时间:2024/06/16 01:48
class Sample: def __enter__(self): print "In __enter__()" return "Foo" def __exit__(self, type,value, trace): print "In __exit__()"def get_sample(): return Sample() with get_sample() as sample: print "sample:",sample
运行结果
In __enter__()
sample: FooIn __exit__()
原理:
1. __enter__()方法被执行
2. __enter__()方法返回的值 - 这个例子中是"Foo",赋值给变量'sample'
3. 执行代码块,打印变量"sample"的值为 "Foo"
4. __exit__()方法被调用
with真正强大之处是它可以处理异常
class Sample: def __enter__(self): return self def __exit__(self, type,value, trace): print "type1:", type print "value:",value print "trace:",trace def do_something(self): bar = 1/0 return bar + 10 with Sample() as sample: sample.do_something()
运行结果:
type1: <type 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <traceback object at 0x0000000002568748>
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\test.py", line 14, in <module>
sample.do_something()
File "C:\Users\Administrator\Desktop\test.py", line 10, in do_something
bar = 1/0
ZeroDivisionError: integer division or modulo by zero
所以,异常处理可以放在__exit__()中
0 0
- python的with是如何工作的
- [python]SGMLParser是如何工作的
- Python 内部:可调用对象是如何工作的
- Learning Python Part III 之 Import 是如何工作的
- Ruby 和 Python 分析器是如何工作的?
- Python如何工作的
- oracle是如何工作的
- Oracle是如何工作的
- Oracle是如何工作的
- Oracle是如何工作的
- Oracle是如何工作的
- SSL是如何工作的?
- 杀毒软件是如何工作的
- SSL是如何工作的?
- Flex是如何工作的
- Oracle是如何工作的
- HttpModule是如何工作的
- SSL是如何工作的
- 初学git:用git bash往github push代码
- 初学git:用git bash往github push代码
- iOS 引用外部静态库(.a文件)时,Category方法无法加载问题
- 初学git:用git bash往github push代码
- test
- python的with是如何工作的
- Hibernate多对多双向关联(Annotation配置)
- 刚进入页面时UIScrollView没有滑动到顶部
- 行为树(Behavior Tree)
- LeetCode #22 Generate Parentheses
- andorid 中 MVP模式 个人理解与运用
- Opencv--形态学图像处理--膨胀与腐蚀,开操作与闭操作
- [bfs] POJ 3009 Curling
- Hibernate多对一双向关联(Annotation配置)