with是个很好玩的东西,其本质是上下文管理。再详细点,就是给当前操作添加一个前置操作和后置操作。
file = open("/tmp/foo.txt")
data = file.read()
file.close()
with open("/tmp/foo.txt") as file:
data = file.read()
对于一个对象,在这里,前置操作:def enter(self) 后置操作:exit(self, type, value, trace)
#!/usr/bin/env python
#with_example01.py
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
关键是后置操作这里,还有3个参数,通过这个,可对错误进行一系列处理。
目前常用的场景1,读取文件
2,数据库事务
with transaction.atomic():
3,可以自己封装一个类,比如之前笔者写过一个限流加统计的程序,需要把执行内容放在笔者before与after方法里面,如果引用with的设计,代码则优雅太多。



