python with/as

本文地址: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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值