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 中使用

  • 相关阅读:
    Angular
    linux mysql 5.7.25 安裝
    J2CACHE 两级缓存框架
    MYSQL 事务测试
    安装配置ftp服务器
    使用docker 安装 GITLIB
    Elastic serarch 安装
    centos firewalld 基本操作【转】
    KAFKA 监控管理界面 KAFKA EAGLE 安装
    redis 的一主二从三哨兵模式
  • 原文地址:https://www.cnblogs.com/leisurelylicht/p/Python-ru-he-pan-duan-dui-xiang-shi-fou-shi-wen-ji.html
Copyright © 2011-2022 走看看