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内置函数isinstance的用法)