Python isinstance() Method

The isinstance() method checks if the object is an instance of the specified class or any of its subclass.

Syntax:

isinstance(object, classinfo)

Parameters:

  1. object: An object to be checked.
  2. classinfo: The class name or a tuple of class names.

Return Value:

Returns True if object is an instance of the specified classinfo, otherwise returns False.

In the following example, the isinstance() method checks for the built-in class instances.

Example: isinstance()
mystr = 'Hello World'
num = 100
flt = 10.2

print(isinstance(mystr, str)) # True
print(isinstance(mystr, int)) # False

print(isinstance(num, int))  # True
print(isinstance(num, str))  # False

print(isinstance(flt, float)) # True
print(isinstance(flt, int))   # False
Output
True
Flase
True
False
True
Flase

The following example checks the instances of the user-defined class.

Example: isinstance() with User-Defined Class
class student:
    name = 'Elon'

std = student()

print(isinstance(std, student))
print(isinstance(std, (student, list, str))) # tuple with class names
print(isinstance(std, list))
Output
True
True
False

In the above example, isinstance(std, (student, list, str)) specifies a tuple with three classes, student, list, and 'str'. It returns True because the specified instance is one of the classes in a tuple.

The following shows the working of isinstance() method with native data types.

Example: isinstance()
cities = ['Mumbai','Chicago','New York']

print(isinstance(cities,list)) 
print(isinstance(cities,(tuple, set))) 
print(isinstance(cities,tuple)) 
Output
True
False
False