Python 3.3.2检查对象是否为文件类型 [英] Python 3.3.2 check that object is of type file

查看:182
本文介绍了Python 3.3.2检查对象是否为文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Python 2.7移植到Python 3.3.2.在Python 2.7中,我曾经能够做类似assert(type(something) == file)的操作,但是似乎在Python 3.3.2中这是错误的.如何在Python 3.3.2中做类似的事情?

I'm porting from Python 2.7 to Python 3.3.2. In Python 2.7, I used to be able to do something like assert(type(something) == file), but it seems that in Python 3.3.2 this is wrong. How do I do a similar thing in Python 3.3.2?

推荐答案

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

这篇关于Python 3.3.2检查对象是否为文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆