想象一下,您在 Python 中打开了某个文件(无论是用于读取、写入还是其他)。我刚刚注意到,当您想关闭该文件时,您可以输入:
somefile.close()
或者您可以输入:
somefile.close
两个版本都是正确的并且它们正确地关闭文件。有什么区别(如果有的话)?
编辑:句子“两个版本都是正确的,并且它们正确地关闭了文件。”是完全错误的。您可以在接受的答案中看到原因。
最佳答案
第一个有用的线索是在 REPL 中运行这两个命令的结果:
>>> f = open("asdf.txt","r")
>>> f.close
<built-in method close of file object at 0x7f38a1da84b0>
>>> f.close()
>>>
因此,f.close
本身返回一个方法,您可以调用该方法。例如,您可以这样写:
>>> x = f.close
>>> x()
关闭文件。
因此,仅输入 f.close
实际上是不够的,因为它仅返回一个允许您关闭文件的方法。我什至可以证明这一点:创建一个文件并将其命名为 example.txt
。
然后尝试以下代码:
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("example.txt","r")
>>> f.close
<built-in method close of file object at 0x7f3d411154b0>
>>> f.readlines()
['this is an example\n', 'file\n']
因此,如果我们只编写f.close
,我们仍然可以使用f.readlines()
:这证明文件实际上并未“关闭”尚未访问!
另一方面,如果我们使用f.close()
:
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("example.txt","r")
>>> f.close()
>>> f.readlines()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
>>>
这就是前面断言的证明:f.close()
和 f.close
实际上不做同样的事情。 f.close()
实际上关闭文件,而 f.close
只是返回一个关闭文件的方法。
在这个答案中,我使用了Python 2.7.4。我不知道 f.close()
和 f.close
的行为在 Python 3+ 中是否有不同。
关于python - somefile.close 和 somefile.close() 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25719138/