您的位置:首页 > 编程语言 > Python开发

python2 type()函数 isinstance()函数

2016-05-04 22:55 525 查看
本文,我们结合python2代码,学习type()函数 isinstance()函数.

1》type()函数

通过type()函数,可以得到一个对象的类型,请看以下示例:

>>> a=8

>>> type(a)

<type 'int'>

>>> a1=67l

>>> type(a1)

<type 'long'>

>>> a2=67L

>>> type(a2)

<type 'long'>

>>> b=9.7

>>> type(b)

<type 'float'>

>>> s='love'

>>> type(s)

<type 'str'>

>>> l=[2,3,4]

>>> type(l)

<type 'list'>

>>> t=(4,5,6)

>>> type(t)

<type 'tuple'>

>>> d={'j':1,'k':2}

>>> type(d)

<type 'dict'>

2》isinstance()函数

isinstance()函数说明如下:

>>> 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.).

第一个参数是:对象(python中一切皆对象)

第二个参数是:自定义的类类型 或 python标准数据类型(int,long,float,list,tuple,dict,str,bool,complex) 或 由二者构成的元组

总结,参数一是对象,参数二是must be a class, type, or tuple of classes and types

2.1>第二个参数是自定义的类类型,对象的类型与参数二的类型相同或对象的类型是参数二的子类就返回True。

class A:

    pass

class B:

    pass

class C(A):

    pass

obj=C()

>>> isinstance(obj,C) #对象obj的类型是C,与参数二一致,返回True

True

>>> isinstance(obj,B)#对象obj的类型是C,与参数二不一致,且C不是B的子类,返回 False

False

>>> isinstance(obj,A)#对象obj的类型是C,与参数二不一致,但C是A的子类,返回True

True

2.2》第二个参数是python标准数据类型,对象的类型与参数二的类型相同则返回True。

>>> isinstance(2,int)

True

>>> isinstance(3L,long)

True

>>> isinstance(3l,long)

True

>>> isinstance(8.9,float)

True

>>> isinstance(True,bool)

True

>>> isinstance('love',str)

True

>>> isinstance(2+3j,complex)

True

>>> isinstance((2,3,4),tuple)

True

>>> isinstance([3,4,5],list)

True

>>> isinstance({'a':1,'b':2},dict)

True

2.3》第三个参数是二者构成的元组,对象的类型在元组中或对象类型的父类在元组中,就返回True。

class A:

    pass

class B:

    pass

class C(A):

    pass

obj=C()

>>> isinstance(obj,(int,str,C,B))#对象obj的类型是C,第二个参数中包含C,因此返回True

True

>>> isinstance(obj,(int,str,A,B))#对象obj的类型是C,C的父类(超类)是A,第二个参数中包含A,因此返回 True

True

>>> isinstance(obj,(int,str,B))#对象obj的类型是C,C的父类是A,C与A均不在参数二中,因此返回False

False

(完)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: