如果函数的第一个参数是第二个参数的实例或子类,则isinstance()
函数返回 true。实际上,我们可以说这个函数用于检查给定的对象是给定类的实例还是子类。
**isinstance(object, classinfo) ** # Where object specify name of the object
isinstance()
参数:接受 2 个参数,其中第一个参数是 string、int、float、long 或自定义类型的对象。
参数 | 描述 | 必需/可选 |
---|---|---|
目标 | 要检查的对象。 | 需要 |
分类(classify) | 类名或类名元组。 | 需要 |
isinstance()
返回值它返回真或假的布尔值。
| 投入 | 返回值 | | 对象是一个实例 | 真实的 | | 对象不是实例 | 错误的 | | classinfo 不是类型或类型元组 | TypeError exception |
isinstance()
方法的示例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
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
isinstance()
的工作方式另一个示例? # 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