isinstance() 函数如果函数的第一个参数是第二个参数的实例或子类,则返回 true。实际上,我们可以说这个函数用于检查给定对象是否是给定类的实例或子类。
isinstance(object, classinfo) # Where object specify name of the object
接受 2 个参数,其中第一个参数是字符串、整数、浮点数、长整型或自定义类型的对象。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 对象 | 要检查的对象。 | 必需 |
| classinfo | 类名或类名元组。 | 必需 |
它返回布尔值 true 或 false。
| 输入 | 返回值 |
|---|---|
| 对象是实例 | true |
| 对象不是实例 | 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,'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
# Python isinstance() function example
class Student:
id = 101
name = "John"
def __init__(self, id, name):
self.id=id
self.name=name
student = Student(1010,"John")
lst = [12,34,5,6,767]
# Calling function
print(isinstance(student, Student)) # isinstance of Student class
print(isinstance(lst, Student))
输出
True False