【问题标题】:Python 3.3.2 check that object is of type filePython 3.3.2 检查对象是否为文件类型
【发布时间】:2013-09-23 17:27:23
【问题描述】:

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

【问题讨论】:

  • FWIW,type(something) == sometype 通常不赞成 isinstance

标签: python file types python-3.x


【解决方案1】:

Python 3 文件对象是 io module 的一部分,在该模块中针对 ABC classes 进行测试:

from io import IOBase

if isinstance(someobj, IOBase):

不要在 Python 2 中使用type(obj) == file;你会改用isinstance(obj, file)。即使这样,您也想测试 capabilities; io ABC 让你做的事情;对于实现了抽象基类定义的所有方法的任何对象,isinstance() function 将返回 True

演示:

>>> from io import IOBase
>>> fh = open('/tmp/demo', 'w')
>>> isinstance(fh, IOBase)
True
>>> isinstance(object(), IOBase)
False

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2012-01-10
    相关资源
    最近更新 更多