Python isinstance() Method
Python isinstance() method is a built-in method. It returns True if object (first argument) is an instance of the given type, else returns False. Type (the second argument) can be a class, subclass or a tuple of type objects.
|object||Object of a class or type which is to be checked.|
|classinfo||Class, Type or tuple of classes.|
It returns a boolean value either True or False.
Error: It returns an error (TypeError), if classinfo is not a standard Python type.
Let’s first understand, how this method works and what does it return?
Python isinstance() Method Example
You can also use this method to check class and object association for other objects like: list or set. See the below example.
Python isinstance() Method Example: Using Tuple
If you are not sure about the type (class) of an object, you can pass tuple of types to provide possible match. See the below example.
In the above example, we passed multiple types as a tuple and method returns True because of type list is present in the tuple.
Python isinstance() Method Example: Using Class Hierarchy
In other scenario, this method can return True if the type (class) is a base class of the object. Like: int is a base class of bool class and object is a base class of int. See the below example.