Introduction to the Python isinstance function
- 2020-05-09 18:49:18
- OfStack
isinstance(object, classinfo)
Determine if the instance is this class or object
object is the variable
classinfo is type (tuple, dict int, float)
Determine whether the variable is of this type
class objA:
pass
A = objA()
B = 'a','v'
C = 'a string'
print isinstance(A, objA)
print isinstance(B, tuple)
print isinstance(C, basestring)
Output results:
True
True
True
Not only that, but you can use the isinstance function to determine whether an object is of a known type.
The instructions for isinstance are as follows:
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
The first parameter is an object, and the second is a type name or a list of type names. The return value is Boolean. Returns True if the type of the object is the same as that of parameter 2. If parameter 2 is a tuple, True is returned if the object type is the same as the type name of 1 in the tuple.
>>>isinstance(lst, list)
True
>>>isinstance(lst, (int, str, list) )
True
In addition, Python can get the type of 1 object, using the type function: > > > lst = [1, 2, 3] > > > type(lst) < type 'list' >