理解 Python 的“with"语句 [英] Understanding the Python 'with' statement
问题描述
我试图了解这些之间是否存在差异,以及差异可能是什么.
I'm trying to understand if there is there a difference between these, and what that difference might be.
方案一:
file_obj = open('test.txt', 'r')
with file_obj as in_file:
print in_file.readlines()
选项二:
with open('test.txt', 'r') as in_file:
print in_file.readlines()
我知道使用选项一,file_obj
在 with 块之后处于关闭状态.
I understand that with Option One, the file_obj
is in a closed state after the with block.
推荐答案
我不知道为什么还没有人提到这个,因为它是 with
的工作方式.与 Python 中的许多语言功能一样,with
在幕后调用 特殊方法,它们已经为内置 Python 对象定义并且可以被用户定义的类覆盖.在 with
的特殊情况下(以及更普遍的上下文管理器),方法是 __enter__
和 __exit__
.
I don't know why no one has mentioned this yet, because it's fundamental to the way with
works. As with many language features in Python, with
behind the scenes calls special methods, which are already defined for built-in Python objects and can be overridden by user-defined classes. In with
's particular case (and context managers more generally), the methods are __enter__
and __exit__
.
请记住,在 Python 中一切都是对象——甚至是文字.这就是为什么您可以执行诸如 'hello'[0]
之类的操作.因此,是否直接使用 open
返回的文件对象并不重要:
Remember that in Python everything is an object -- even literals. This is why you can do things like 'hello'[0]
. Thus, it does not matter whether you use the file object directly as returned by open
:
with open('filename.txt') as infile:
for line in infile:
print(line)
或者先用一个不同的名字存储(例如打断一个长行):
or store it first with a different name (for example to break up a long line):
the_file = open('filename' + some_var + '.txt')
with the_file as infile:
for line in infile:
print(line)
因为最终的结果是the_file
、infile
和open
的返回值都指向同一个对象,就是这样with
正在调用 __enter__
和 __exit__
方法.内置文件对象的 __exit__
方法用于关闭文件.
Because the end result is that the_file
, infile
, and the return value of open
all point to the same object, and that's what with
is calling the __enter__
and __exit__
methods on. The built-in file object's __exit__
method is what closes the file.
这篇关于理解 Python 的“with"语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!