很好的Python,带有语句解释
我尝试过谷歌和其他地方,但我似乎找不到 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个很好的例子:
当执行“with”语句时,Python 计算表达式,对结果值调用 enter 方法(称为“上下文保护”),并分配任何 >enter 返回到 as 给出的变量。然后,Python 将执行代码主体,无论该代码中发生什么,都会调用守卫对象的 exit 方法。
Here's a good example:
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.