python内置函数isinstance的用法

isinstance说明如下:
isinstance(object, class-or-type-or-tuple) -> bool

Return whether an object is an instance of a class or of a subclass thereof.  
With a type as second argument, return whether that is the object's type.  
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for  
isinstance(x, A) or isinstance(x, B) or ... (etc.).  

其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。若对象的类型与参数二的类型相同则返回True。若参数二为一个元组,则若对象类型与元组中类型名之一相同即返回True。

例一

>>>a = 4
>>>isinstance (a,int)
True
>>>isinstance (a,str)
False
>>>isinstance (a,(str,int,list))
True

例二

>>>a = "b"
>>>isinstance(a,str)
True
>>>isinstance(a,int)
False
>>>isinstance(a,(int,list,float))
False
>>>isinstance(a,(int,list,float,str))
True

例三

'''取出一个列表中的元素,其中有的元素可能是列表或者元祖'''

def myextend(alist):
    blist = []
    for item in alist:
        if isinstance(item, (list, tuple)):
            blist.extend(myextend(item))
        else:
            blist.append(item)
    return blist

alist = [1, 2, [3, 4], 5, [6, ["7", "8"], 9], 10, (11, 12)]
blist = myextend(alist)
print(blist)

>>> [1, 2, 3, 4, 5, 6, '7', '8', 9, 10, 11, 12]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 内置函数Python解释器内置了许多功能和类型,总是可用的。他们是按字母顺序列在这里。 abs(x)返回一个数的绝...
    uangianlap阅读 5,027评论 0 0
  • Python 是一种相当高级的语言,通过 Python 解释器把符合语法的程序代码转换成 CPU 能够执行的机器码...
    Python程序媛阅读 5,929评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,314评论 19 139
  • 1. abs(x) abs()函数返回数字(可为普通型、长整型或浮点型)的绝对值。如果给出复数,返回值就是该复数的...
    chen_000阅读 3,038评论 0 0
  • 1. 最终实现的效果 2. 逻辑思路分析图 3. 模块分类 4. 需要使用的第三方包插件 5. 模块分类 app....
    Robyn_Luo阅读 1,300评论 0 0