isinstance()的作用
isinstance() 函数来判断一个对象是否是一个已知的类型。
isinstance() 解释
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) or a Union Type of multiple types, 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.
如果 object 参数是 classinfo 参数的实例,或其(直接、间接或 virtual )子类的实例,则返回 True。 如果 object 不是给定类型的对象,则总是返回 False。如果 classinfo 是类型对象的元组(或由该类元组递归生成)或多个类型的 Union Type,那么当 object 是其中任一类型的实例时就会返回 True。如果 classinfo 不是某个类型或类型元组,将会触发 TypeError 异常。
和type()的区别
- type() 不会认为子类是一种父类类型,不考虑继承关系。
- isinstance() 会认为子类是一种父类类型,考虑继承关系。
isinstance() 实例参考
>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list)) # 是元组中的一个返回 True
True
# isinstance()与type()的区别
class A:
pass
class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False