更新时间:2023-11-28 14:54:04
Python 3文件对象是 io
模块,针对该模块中的 ABC类进行测试:>
Python 3 file objects are part of the io
module, test against ABC classes in that module:
from io import IOBase
if isinstance(someobj, IOBase):
在Python 2中不要使用type(obj) == file
;您应该使用isinstance(obj, file)
代替.即使那样,您仍要测试功能; io
ABC允许您执行的操作; isinstance()
函数将为实现抽象方法的所有方法的任何对象返回True
.基类定义.
Don't use type(obj) == file
in Python 2; you'd use isinstance(obj, file)
instead. Even then, you would want to test for the capabilities; something the io
ABCs let you do; the isinstance()
function will return True
for any object that implements all the methods the Abstract Base Class defines.
演示:
>>> from io import IOBase
>>> fh = open('/tmp/demo', 'w')
>>> isinstance(fh, IOBase)
True
>>> isinstance(object(), IOBase)
False