如何检查对象是否是带有isinstance()的文件?

Tri*_*max 9 python class python-3.x

如何检查对象是否是文件?

>>> f = open("locus.txt", "r")
>>> type(f)
<class '_io.TextIOWrapper'>
>>> isinstance(f, TextIOWrapper)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    isinstance(f, TextIOWrapper)
NameError: name 'TextIOWrapper' is not defined
>>> isinstance(f, _io.TextIOWrapper)
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    isinstance(f, _io.TextIOWrapper)
NameError: name '_io' is not defined
>>> isinstance(f, _io)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    isinstance(f, _io)
NameError: name '_io' is not defined
>>> 
Run Code Online (Sandbox Code Playgroud)

我有f一个文本文件的变量.当我打印fPython3解释器的类型时显示'_io.TextIOWrapper',但如果我用isinstance()函数检查它会抛出异常:NameError.

Mar*_*ers 14

_ioio模块的C实现.使用io.IOBase直接的子类,导入模块后:

>>> import io
>>> f = open("tests.py", "r")
>>> isinstance(f, io.IOBase)
True
Run Code Online (Sandbox Code Playgroud)

  • 是的,请参阅 [类层次结构部分](https://docs.python.org/3/library/io.html#class-hierarchy),这就是基类的用途(它们是 ABC,因此它们测试*功能*,而不仅仅是子类)。 (2认同)