python之with statement

with statement 从python2.5就出现了到python2.6成为了默认关键字,查看文档发现它实质上是控制流语句用来简化 try-cache-finally语句,主要用法是实现一个类中的__enter__(self)和__exit__(self,type,value,traceback)方法的.

语法格式是:with_stmt ::= "with" expression ["as" target] ":" suite

执行顺序如下:

首先执行类中的__enter()方法不管运行结果如何都会执行__exit__()这个方法的,通常用于读取文件操作将文件句柄的关闭放在__exit__()中。

class controlled_execution():
    def __enter__(self):
        return "liujijun"
    def __exit__(self,type,value,trackback):
        print "__exit__"
    

with controlled_execution() as thing:
    print thing
    print "with"
    

你可能感兴趣的:(python之with statement)