良好的Python与声明解释

时间:2012-01-24 17:14:08

标签: python with-statement

我已经尝试了谷歌和其他地方,但我似乎无法找到with声明的良好解释。在什么情况下有用?我知道文件是如何工作的,但是如何使用呢?

1 个答案:

答案 0 :(得分:4)

这是一个很好的例子:

  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”语句时,Python会对表达式求值,在结果值(称为“上下文保护”)上调用 enter 方法,然后分配输入的内容返回as给出的变量。然后Python将执行代码体,无论代码中发生什么,都要调用guard对象的 exit 方法。