Python判断对象是否为文件对象的三种方法
本文介绍Python中判断对象是否为文件对象的三种常用方法。第一种通过比较type是否等于file,但无法识别子类;第二种使用isinstance()函数,可正确识别继承自file的子类;第三种基于鸭子类型思想,检查对象是否具备read、write和close等可调用属性。
Python判断文件对象的三种方法
在开发过程中,文件操作是极为常见的场景。面对各种对象,如何准确判断一个对象是否属于文件对象(file object)?下面总结三种常见的判断方式。
方法一:直接比较类型
第一种思路是直接检查对象的type属性是否等于file。
方法一:直接比较类型
>>> fp = open(r"/tmp/pythontab.com")
>>> type(fp)
<type 'file'>
>>> type(fp) == file
True
需要注意的是,这种方法对于从file类继承而来的子类并不适用。具体表现见下面的示例。
class fileDetect(file):
pass # 中间代码无所谓,直接跳过不处理
fp2 = fileDetect(r"/tmp/pythontab.com")
fileType = type(fp2)
print(fileType)
运行结果如下:
<class '__main__.fileDetect'>
方法二:使用isinstance函数
判断一个对象是否为文件对象,可以直接利用isinstance()函数进行验证。
在下面的代码中,通过open()函数获取的对象fp,其类型为file,因此它是file的实例;而变量filename类型为str,显然不是file的实例。
方法二:使用isinstance函数
>>> isinstance(fp, file)
True
>>> isinstance(fp2, file)
True
>>> filename = r"/tmp/pythontab.com"
>>> type(filename)
<type 'str'>
>>> isinstance(filename, file)
False
方法三:基于接口的推测法
在Python中,类型的严格定义并非绝对关键,更重要的是对象所具备的“接口”。如果某个对象的行为像鸭子(具备走路和叫声的特征),那么在相关行为上我们就视其为鸭子。
基于这一思路,我们可以采用第三种判断方法:检查一个对象是否拥有可调用的read、write和close方法(或属性)。
参考文档:http://docs.python.org/glossary.html#term-file-object
方法三:基于接口的推测法
def isfile(f):
"""
Check if object 'f' is readable file-like
that it has callable attributes 'read' , 'write' and 'close'
"""
try:
if isinstance(getattr(f, "read"), collections.Callable) \
and isinstance(getattr(f, "write"), collections.Callable) \
and isinstance(getattr(f, "close"), collections.Callable):
return True
except AttributeError:
pass
return False
以上就是本文的全部内容,希望对各位的学习有所帮助,也欢迎大家继续支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









