[转帖]python判断对象是否为文件对象(file object)_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3399 | 回复: 0   主题: [转帖]python判断对象是否为文件对象(file object)        下一篇 
lijia.peng
注册用户
等级:上尉
经验:753
发帖:66
精华:0
注册:2013-11-5
状态:离线
发送短消息息给lijia.peng 加好友    发送短消息息给lijia.peng 发消息
发表于: IP:您无权察看 2013-11-12 11:19:53 | [全部帖] [楼主帖] 楼主

方法1:比较type

第一种方法,就是判断对象的type是否为file,但该方法对于从file继承而来的子类不适用:

[python]
>>> f = open(r"D:\2.zip")
>>> type(f)
<type 'file'>
>>> type(f) == file
True
>>> class MyFile(file):
pass
>>> mf = MyFile(r"D:\2.txt")
>>> type(mf)
<class '__main__.MyFile'>
>>> type(mf) == file
False


方法2:isinstance

要判断一个对象是否为文件对象(file object),可以直接用isinstance()判断。

如下代码中,open得到的对象f类型为file,当然是file的实例,而filename类型为str,自然不是file的实例

[python]
>>> isinstance(f, file)
True
>>> isinstance(mf, file)
True
>>> filename = r"D:\2.zip"
>>> type(filename)
<type 'str'>
>>> isinstance(filename, file)
False


方法3:duck like(像鸭子一样)

在python中,类型并没有那么重要,重要的是”接口“。如果它走路像鸭子,叫声也像鸭子,我们就认为它是鸭子(起码在走路和叫声这样的行为上)。

按照这个思路我们就有了第3中判断方法:判断一个对象是否具有可调用的read,write,close方法(属性)。

[python]
def isfilelike(f):
"""
Check if object 'f' is readable file-like
that it has callable attributes 'read' , 'write' and 'closer'
"""
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


其他:读/写方式打开的”类文件“对象

只从文件读入数据的时候只要检查对象是否具有read,close;相应的只往文件中写入数据的时候仅需要检查对象是否具有write,close方法。就像如果仅从走路方式判断它是否为鸭子,只检查是否”走路像鸭子“;如果仅从声音来判断,则仅需要检查是否”叫声像鸭子“。

[python]
def isfilelike_r(f):
"""
Check if object 'f' is readable file-like
that it has callable attributes 'read' and 'close'
"""
try:
if isinstance(getattr(f, "read"), collections.Callable) \
and isinstance(getattr(f, "close"), collections.Callable):
return True
except AttributeError:
pass
return False
def isfilelike_w(f):
"""
Check if object 'f' is readable file-like
that it has callable attributes 'write' and 'close'
"""
try:
if isinstance(getattr(f, "write"), collections.Callable) \
and isinstance(getattr(f, "close"), collections.Callable):
return True
except AttributeError:
pass
return False


另:为什么用getattr而不是hasattr    www.2cto.com
这里为什么不用hasattr,而是用getattr来承担抛出AttributeError的风险呢?

一方面,hasattr就是直接调用getattr来看是否抛出了AttributeError,如果没有抛出就返回True,否则返回False,参看这里。既然如此,我们就可以自己来完成这个工作。

另一方面,这样我们可以得到属性对象,然后可以用isinstance判断是否为collections.Callable的实例。两者结合,如果有该属性,并可以被调用,则返回True。




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论