Python built-in function isinstance() function introduction

Python built-in function isinstance() function introduction

The isinstance() function is a Python built-in function to determine whether an object is a known type, and the return value is a boolean True or False. Its grammatical format:

isinstance(object, classinfo)

[Official statement https://docs.python.org/zh-cn/3/library/functions.html#isinstance 

Return True if the object argument is an instance of the classinfo argument, or an instance of its (direct, indirect, or virtual) subclass. Always returns False if object is not an object of the given type. If classinfo is a tuple of type objects (or recursively generated from that class tuple) or a union of types, then return True if object is an instance of either type. If classinfo is not a type or tuple of types, a TypeError exception will be raised.

The official statement is not easy to understand, so let's explain it below.

parameter

object -- the instance object, which is the object to be type-checked.

classinfo -- can be a direct or indirect class name, a primitive type, or a tuple of them.

For basic types, classinfo can be: int, float, bool, complex, str (string), list, dict (dictionary), set, tuple. The classinfo parameter can also take a tuple composed of multiple types of objects as a parameter. When the classinfo parameter is multiple types of objects, the isinstance() function will check each type of object one by one. As long as the object belongs to any one of the types, it will return True .

>>>a = 2 
>>> isinstance (a,int) 
True 
>>> isinstance (a,str) 
False 
>>> isinstance (a,(str,int,list)) # 是元组中的一个返回 True
True

The isinstance() function can also be used to determine whether an object is an instance of a certain class or its subclasses.

Here is the case for class

# isinstance()函数用于类的示例
class Animal:
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

dog = Dog()
cat = Cat()

print(isinstance(dog, Dog))     # 返回True, dog是Dog类的实例
print(isinstance(cat, Animal))  # 返回True, cat是Animal类的子类Cat的实例

In the above example, the isinstance() function checks the types of the dog and cat objects respectively, and the classinfo parameters passed in are Dog and Animal, respectively, to determine whether they are instances of these two classes.

Next, give another example for the class

class A:
    pass

class B(A):
    pass

class C:
    pass

print(isinstance(A(), A))  # 返回:True
print(isinstance(B(), A))  # 返回:True
print(isinstance(C(), A))  # 返回:False

Guess you like

Origin blog.csdn.net/cnds123/article/details/131112054