zoukankan      html  css  js  c++  java
  • Python 如何判断对象是否是文件对象

    Python2

    Python2 有一种比较可靠的方式就是判断对象的类型是否是file类型。因此可以使用type函数或者isinstance函数实现。

    type

    当然type函数无法对继承得来的子类起作用

    >>> f = open('./text', 'w')
    >>> type(f)
    <type 'file'>
    >>> type(f) == file
    True
    
    >>> class MyFile(file):
    ...     pass
    ...
    >>> mf = MyFile('./text')
    >>> type(mf)
    <class '__main__.MyFile'>
    >>> type(mf) == file
    False
    

    isinstance

    isinstancne是推荐的判断类型时方法,通常情况下都应该选择此方法。isinstance也可以对子类起作用。

    >>> f = open('./text', 'w')
    >>> isinstance(f, file)
    True
    
    >>> class MyFile(file):
    ...     pass
    ...
    >>> mf = MyFile('./text')
    >>> isinstance(mf, file)
    True
    

    Python3

    在 Python3 中,官方取消了file这一对象类型,使得 python2 中的判断方法无法在 Python3 中使用。

    因此在 Python3 中只能通过鸭子类型的概念判断对象是否实现了可调用的``read, write, close方法, 来判断对象是否是一个文件对象了。

    def isfilelike(f):
        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
    

    当然这个方法也可以在 python2 中使用

  • 相关阅读:
    numpy计算路线距离
    WebApi安全性 使用TOKEN+签名验证
    从SQL查询分析器中读取EXCEL中的内容
    Autofac应用总结
    Visual Studio提示“无法启动IIS Express Web服务器”的解决方法
    架构 : 三层架构、MVC、MVP、MVVM
    Asp.Net MVC :路由器
    myeclipse10安装egit和使用
    myeclipse10.7安装git插件
    SQLite之C#连接SQLite
  • 原文地址:https://www.cnblogs.com/leisurelylicht/p/Python-ru-he-pan-duan-dui-xiang-shi-fou-shi-wen-ji.html
Copyright © 2011-2022 走看看