您的位置:首页 > 编程语言 > Python开发

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__()中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: