python的with是如何工作的
2015-08-05 12:05
811 查看
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: Foo
In __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__()中
相关文章推荐
- python __name__
- python code
- python:解析html(HTMLParser、SGMLParser)
- python的enumerate()
- PYTHON开发入门与实战14-基于EXTJS的界面
- python的zip()
- PYTHON开发入门与实战14-基于EXTJS的界面
- PYTHON开发入门与实战14-基于EXTJS的界面
- python字典排序
- python解决斐波拉契问题的n种方法
- 【python工具篇】pip和pypi
- python安装各种插件
- python中str()与repr()的区别
- 《父与子的编程之旅-与小卡特一起学python》第18章
- 从零开始学Python
- python中range和xrnage的区别
- 从零开始学Python
- 从零开始学Python
- 从零开始学Python
- python多线程编程(3): 使用互斥锁同步线程