好的Python with语句解释

3 投票
1 回答
548 浏览
提问于 2025-04-17 10:59

我试过谷歌和其他地方,但似乎找不到关于with语句的好解释。它在什么情况下有用呢?我明白它在处理文件时是怎么工作的,但还有其他什么用法呢?

1 个回答

3

这里有个很好的例子:

  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方法(这个值叫做“上下文管理器”)。接着,Python会把enter方法返回的结果赋值给“as”后面的变量。然后,Python会执行这个代码块里的内容,不管里面发生什么,最后都会调用这个上下文管理器的exit方法。

撰写回答