在Python 2.7中,我得到了以下结果:
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, file))
...
True
在python3.5中,我得到:
^{pr2}$所以,我查看Python文档,发现在python3.5中,文件的类型是io.IOBase
(或某些子类)。让我知道:
>>> import io
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, io.IOBase))
...
True
但当我尝试使用Python 2.7时:
>>> import io
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, io.IOBase))
...
False
我现在很困惑。看看documentation,我觉得Python2.7应该报告True
。在
很明显我遗漏了一些基本的东西,也许是因为现在是东部时间下午6:30,但是我有两个相关的问题:
isinstance(fin, io.IOBase)
报告False
?在
从链接的文档:
所以它们在python2.x中是不一样的
至于第二部分,这在《Python2》和《Python3》中都很管用,虽然不是世界上最漂亮的东西:
对于Python2
对于Python3
^{pr2}$(编辑:我以前的解决方案测试io.TextIOWrapper,它只适用于以文本模式打开的文件。请参见描述python3类层次结构的https://docs.python.org/3/library/io.html#class-hierarchy)。在
相关问题 更多 >
编程相关推荐