This article introduces the Python built-in isinstance function in detail:
Isinstance (object, classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. if object is not an object of the given type, the function always returns false. if classinfo is a tuple of type objects (or recursively, other such tuples), return true if object is an instance of any of the types. if classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.
Note:
1. the function is used to determine whether an object is an instance of a type object. the object parameter indicates the object to be checked, and the calssinfo parameter indicates the type object.
2. if the object parameter is an instance of the classinfo type object (or a direct, indirect, or virtual subclass of the classinfo class object), True is returned.
>>> Isinstance (1, int) True >>> isinstance (1, str) False # define 3 categories: C inherits B, B inherits A >>> class: pass >>> class B (A): pass >>> class C (B): pass >>> a = A () >>>> B = B () >>> c = C () >>> isinstance (a, A) # direct instance True >>> isinstance (a, B) False >>> isinstance (B,) # Subclass instance True >>> isinstance (c, A) # grandson class instance True
3. if the object parameter is a type object, False is always returned.
>>> isinstance(str,str)False >>> isinstance(bool,int)False
4. if a classinfo object is a combination of multiple types of objects, True is returned if the object is an instance of any type of object of the tuples. otherwise, False is returned.
>>> isinstance(a,(B,C))False>>> isinstance(a,(A,B,C))True
5. if a classinfo object is not a type object or a tuples composed of multiple types of objects, a TypeError is returned ).
>>> isinstance(a,[A,B,C])Traceback (most recent call last): File "
", line 1, in
isinstance(a,[A,B,C])TypeError: isinstance() arg 2 must be a type or tuple of types
The above is a detailed description of the Python built-in isinstance function. For more information, see other related articles in the first PHP community!