isinstance()函数检查对象(第一个参数)是否是classinfo类(第二个参数)的实例或子类。
isinstance()的语法为:
isinstance(object, classinfo)
isinstance()具有两个参数:
object- object待检查
classinfo -类,类型或元组
isinstance()返回:
True如果object是类的实例或子类,或元组的任何元素
False 除此以外
如果classinfo不是类型或元组类型,则会引发TypeError异常。
class Foo: a = 5 fooInstance = Foo() print(isinstance(fooInstance, Foo)) print(isinstance(fooInstance, (list, tuple))) print(isinstance(fooInstance, (list, tuple, Foo)))
运行该程序时,输出为:
True False True
numbers = [1, 2, 3] result = isinstance(numbers, list) print(numbers,'是 list 实例?', result) result = isinstance(numbers, dict) print(numbers,'是 dict 实例?', result) result = isinstance(numbers, (dict, list)) print(numbers,'是 dict 或 list 实例?', result) number = 5 result = isinstance(number, list) print(number,'是 list 实例?', result) result = isinstance(number, int) print(number,'是 int 实例?', result)
运行该程序时,输出为:
[1, 2, 3] 是 list 实例? True [1, 2, 3] 是 dict 实例? False [1, 2, 3] 是 dict 或 list 实例? True 5 是 list 实例? False 5 是 int 实例? True