为什么在Python中open()比file()更好?

2024-04-29 04:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Python - When to use file vs open

从官方的python文档中

http://docs.python.org/library/functions.html#file

When opening a file, it’s preferable to use open() instead of invoking this constructor directly

但这并没有说明原因。在


Tags: to文档orghttpdocs官方uselibrary
1条回答
网友
1楼 · 发布于 2024-04-29 04:19:44

The Zen of Python

There should be one and preferably only one obvious way to do it.

所以file或{}应该走。在

>>> type(file)
<type 'type'>
>>> type(open)
<type 'builtin_function_or_method'>

open是一个可以返回任何内容的函数。file()只返回file对象。在

尽管在python2上,open似乎只返回file对象。在Python2.5之前,file和{}是同一个对象。在

正如@gnibbler在评论中建议的那样,file存在的最初原因可能是使用它作为基类的名称。在

另外,file()原则上可以返回其他类型,例如int()在早期Python版本上所做的:

^{pr2}$

这个答案与@Ryan's answer非常相似。在

另外BDFL said

"The file class is new in Python 2.2. It represents the type (class) of objects returned by the built-in open() function. Its constructor is an alias for open(), but for future and backwards compatibility, open() remains preferred." (emphasis mine)

相关问题 更多 >