2024-04-29 04:19:44 发布
网友
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
但这并没有说明原因。在
The Zen of Python:
There should be one and preferably only one obvious way to do it.
所以file或{}应该走。在
file
>>> type(file) <type 'type'> >>> type(open) <type 'builtin_function_or_method'>
open是一个可以返回任何内容的函数。file()只返回file对象。在
open
file()
尽管在python2上,open似乎只返回file对象。在Python2.5之前,file和{}是同一个对象。在
正如@gnibbler在评论中建议的那样,file存在的最初原因可能是使用它作为基类的名称。在
另外,file()原则上可以返回其他类型,例如int()在早期Python版本上所做的:
int()
这个答案与@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)
The Zen of Python:
所以}应该走。在
file
或{open
是一个可以返回任何内容的函数。file()
只返回file
对象。在尽管在python2上,}是同一个对象。在
open
似乎只返回file
对象。在Python2.5之前,file
和{正如@gnibbler在评论中建议的那样,
file
存在的最初原因可能是使用它作为基类的名称。在另外,
^{pr2}$file()
原则上可以返回其他类型,例如int()
在早期Python版本上所做的:这个答案与@Ryan's answer非常相似。在
另外BDFL said:
相关问题 更多 >
编程相关推荐