📜  Python isinstance()

📅  最后修改于: 2020-09-20 04:13:10             🧑  作者: Mango

isinstance() 函数检查对象(第一个参数)是否是classinfo类(第二个参数)的实例或子类。

isinstance()的语法为:

isinstance(object, classinfo)

isinstance()参数

isinstance()具有两个参数:

  1. 对象-要检查的object
  2. classinfo-类,类型或类和类型的元组

从isinstance()返回值

isinstance()返回:

  1. 如果object是一个类的实例或子类或元组的任何元素,则为True
  2. 否则为False

如果classinfo不是类型或类型的元组,则会引发TypeError异常。

示例1:isinstance()如何工作?

class Foo:
  a = 5
  
fooInstance = Foo()

print(isinstance(fooInstance, Foo))
print(isinstance(fooInstance, (list, tuple)))
print(isinstance(fooInstance, (list, tuple, Foo)))

输出

True
False
True

示例2:使用本机类型的isinstance()工作

numbers = [1, 2, 3]

result = isinstance(numbers, list)
print(numbers,'instance of list?', result)

result = isinstance(numbers, dict)
print(numbers,'instance of dict?', result)

result = isinstance(numbers, (dict, list))
print(numbers,'instance of dict or list?', result)

number = 5

result = isinstance(number, list)
print(number,'instance of list?', result)

result = isinstance(number, int)
print(number,'instance of int?', result)

输出

[1, 2, 3] instance of list? True
[1, 2, 3] instance of dict? False
[1, 2, 3] instance of dict or list? True
5 instance of list? False
5 instance of int? True