什么是python关键字“with"?用于? [英] What is the python keyword "with" used for?

查看:44
本文介绍了什么是python关键字“with"?用于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 关键字with"是做什么用的?

示例来自:http://docs.python.org/tutorial/inputoutput.html

<预><代码>>>>with open('/tmp/workfile', 'r') as f:... read_data = f.read()>>>f.关闭真的

解决方案

在 python 中,with 关键字用于处理非托管资源(如文件流).它类似于 VB.NET 和 C# 中的 using 语句.它允许您确保资源被清理".当使用它的代码完成运行时,即使抛出异常.它为 try/finally 块提供语法糖".

来自 Python 文档:><块引用>

with 语句阐明了以前使用 try...finally 块来确保执行清理代码的代码.在本节中,我将讨论常用的语句.在下一节中,我将检查实现细节并展示如何编写用于此语句的对象.

with 语句是一个控制流结构,其基本结构是:

 with expression [as variable]:带块

对表达式求值,它应该产生一个支持上下文管理协议的对象(即具有 __enter__()__exit__() 方法).

更新根据 Scott Wisniewski 的评论修复了 VB 标注.我确实将 withusing 混淆了.

What is the python keyword "with" used for?

Example from: http://docs.python.org/tutorial/inputoutput.html

>>> with open('/tmp/workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

解决方案

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with with using.

这篇关于什么是python关键字“with"?用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆