本文地址:http://blog.youkuaiyun.com/spch2008/article/details/9340247
看代码时遇到with/as语句,查阅相关资料,现总结如下:
with/as是一种异常相关语句,可虑下列代码:
set things up
try:
do something
finally:
tear things down
"set things up“可以是打开一个文件,"tear things down"为关闭文件。try-finally语句保证
"tear things down"总被执行,即使do something抛出异常。
def controlled_execution(callback):
set things up
try:
callback(thing)
finally:
tear things down
def my_function(thing):
do something
controlled_execution(my_function)
需要不同功能时,需要定义新函数,然后传入controlled_execution,稍微有些繁琐。
通过with,进一步简化上述操作。
class controlled_execution:
def __enter__(self):
set things up
return thing
def __exit__(self, type, value, traceback):
tear things down
with controlled_execution() as thing:
some code
with语句,执行controlled_execution中的__enter__方法,做相应的准备工作,并将返回值付给as后变量,即thing。
执行代码体,不论代码体是否发生异常,都会执行controlled_execution中的__exit__方法进行收尾工作。
另外__exit__可以通过返回true来抑制异常传播。例如,吞下类型错误异常,放行其它异常。
def __exit__(self, type, value, traceback):
return isinstance(value, TypeError)
来个例子:
class controlled_execution:
def __enter__(self):
print "starting with block"
return self
def __exit__(self, type, value, traceback):
print "exited normally"
def message(self, args):
print 'running'
print args
with controlled_execution() as action:
action.message("test")