视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
Python内置isinstance函数详细介绍
2020-11-27 14:25:12 责编:小采
文档


英文文档:

isinstance(object, classinfo)

Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false. If classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.

说明:

  1. 函数功能用于判断对象是否是类型对象的实例,object参数表示需要检查的对象,calssinfo参数表示类型对象。

  2. 如果object参数是classinfo类型对象(或者classinfo类对象的直接、间接、虚拟子类)的实例,返回True。

>>> isinstance(1,int)
True
>>> isinstance(1,str)
False

# 定义3各类:C继承B,B继承A
>>> class A:
 pass

>>> class B(A):
 pass

>>> class C(B):
 pass

>>> a = A()
>>> b = B()
>>> c = C()
>>> isinstance(a,A) #直接实例
True
>>> isinstance(a,B)
False
>>> isinstance(b,A) #子类实例 
True
>>> isinstance(c,A) #孙子类实例
True

  3. 如果object参数传入的是类型对象,则始终返回False。

>>> isinstance(str,str)
False 
>>> isinstance(bool,int)
False

  4. 如果classinfo类型对象,是多个类型对象组成的元组,如果object对象是元组的任一类型对象中实例,则返回True,否则返回False。

>>> isinstance(a,(B,C))
False
>>> isinstance(a,(A,B,C))
True

  5. 如果classinfo类型对象,不是一个类型对象或者由多个类型对象组成的元组,则会报错(TypeError)。

>>> isinstance(a,[A,B,C])
Traceback (most recent call last):
 File "<pyshell#23>", line 1, in <module>
 isinstance(a,[A,B,C])
TypeError: isinstance() arg 2 must be a type or tuple of types

下载本文
显示全文
专题