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:
- object: An object to be checked.
- 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.
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
True
Flase
True
False
True
Flase
The following example checks the instances of the 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))
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.
cities = ['Mumbai','Chicago','New York']
print(isinstance(cities,list))
print(isinstance(cities,(tuple, set)))
print(isinstance(cities,tuple))
True
False
False