python isinstance
程序员文章站
2024-03-17 18:07:10
...
isinstance(object,type)常用来判断一个对象是否是一个已知的类型。
其第参数object为对象,第二个参数type为类型名如int、str,或类型名的一个列表如[int,str,tuple,list,float]。
其返回值为布尔型(True 或 Flase)。若对象的类型与参数二的类型相同则返回True。若参数type为一个元组,参数object类型与元组中类型名之一相同也返回True。
>>> help(isinstance)
Help on built-in function isinstance in module __builtin__:
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.).
>>>
1、参数object为常用类型:
>>> a = 2
>>> isinstance(a,int)
True
>>> isinstance(a,float)
False
>>> type(a)
<type 'int'>
>>> s = 'abc'
>>> type(s)
<type 'str'>
>>> isinstance(s,str)
True
>>> isinstance(2.5,float)
True
2、参数object为列表、元祖、字典:
>>> lst = [1,2,'3',4]
>>> type(lst)
<type 'list'>
>>> isinstance(lst,list)
True
>>> tpl = (5,6,7)
>>> type(tpl)
<type 'tuple'>
>>> isinstance(tpl,tuple)
True
>>> dic = {a:8,b:9,c:10}
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
dic = {a:8,b:9,c:10}
NameError: name 'a' is not defined
>>> dic = {'a':8,'b':9,'c':10}
>>> isinstance(dic,dict)
True
>>>
3、参数object为类:(建议使用isinstance判断对象,少用type。)>>> class BaseClass:
pass
>>> class SubClass:
pass
>>> isinstance(BaseClass(),BaseClass)
True
>>> type(BaseClass())
<type 'instance'>
>>> type(BaseClass()) == BaseClass
False
>>> c = SubClass()
>>> isinstance(c,SubClass)
True
>>>
4、参数type为元祖:
>>>
>>> isinstance(c,(int,str,list))
False
>>> isinstance(c,(int,str,list,SubClass))
True
>>> t = (int,str,list,SubClass)
>>> isinstance(c,t)
True
>>>
上一篇: 体验/JQuery基础一