版本
E:\Projects\testTool>python --version
Python 3.6.2
定义
先看下官网是如何定义isinstance函数的。
isinstance(object, classinfo)
Reuturn 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 a raised.
大致翻译一下:
如果object参数是classinfo参数的实例,或者object参数是classinfo的直接或间接或虚拟子类实例,函数则返回True, 反之返回False。 如果classinfo参数是一个包含多个类的元组,只要对象是元组中某一类的实例,同样返回True, 如果classinfo参数不是一个类,函数则会抛出TypeError错误。
总而言之,这就是判断对象是否是一个已知的类型
示例
1.obeject参数是classinfo参数的实例
>>> a = 8
>>> isinstance(a, int)
2.obeject参数是classinfo参数的实例,并且classinfo是一个元组
返回True:
>>> a = 8
>>> isinstance(a, (int, str, list))
True
返回:False
>>> a = 8
>>> isinstance(a, (str, list, dict))
False
3.object参数是继承自classinfo参数
>>> isinstance(int, type)
True
>>> class A:
... pass
...
>>> class B(A):
... pass
...
>>> class C(B):
... pass
...
>>> isinstance(B(), A)
True
>>> isinstance(C(), A)
True
>>> isinstance(A, object)
True
>>> isinstance(A(), A)
True