很好的Python,带有语句解释

发布于 2024-12-28 20:23:17 字数 85 浏览 1 评论 0原文

我尝试过谷歌和其他地方,但我似乎找不到 with 语句的良好解释。在什么情况下有用?我知道它是如何处理文件的,但是它还能怎么用呢?

I've tried google and other places but I can't seem to find a good explanation of the with statement. In what situations is it useful? I get how it works with files but how else could it be used?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌逼全场 2025-01-04 20:23:17

这是一个很好的例子:

  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 方法(称为“上下文保护”),并分配任何 >enter 返回到 as 给出的变量。然后,Python 将执行代码主体,无论该代码中发生什么,都会调用守卫对象的 exit 方法。

Here's a good example:

  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

When the “with” statement is executed, Python evaluates the expression, calls the enter method on the resulting value (which is called a “context guard”), and assigns whatever enter returns to the variable given by as. Python will then execute the code body, and no matter what happens in that code, call the guard object’s exit method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文