The isinstance()
function is used to determine whether an object is an instance of a specified class or the object is an instance of one of the classes in a given tuple of classes.
Syntax:
isinstance(object, cls)
or
isinstance(object, tuple_of_classes)
The function returns a Boolean value; True
if the object is an instance of the specified class or is an instance of one of the given classes( if the second argument is a tuple). It returns False
otherwise.
This function is commonly used to check whether the given object belongs to a certain type.
isinstance('Hello', str)
//True
isinstance(5, int)
//True
isinstance(True, bool)
//True
isinstance(3.142, int)
//False
isinstance(3.142, float)
//True
isinstance([1, 2, 3,4], list)
//True
isinstance({}, set)
//False
isinstance({}, dict)
//True
The function also returns True
if the given class is a base class of the class that the object belongs to. For example calling isinstance(False, int)
will return True
because the value False belongs to the bool
type which is a subclass of the int
type.
example:
isinstance(bool, int)
//True
isinstance(True, bool)
//True
isinstance(True, int)
//True
Using a tuple of types
isinstance(1, (list, int, tuple))
//True
isinstance([1, 2, 3], (tuple, set, dict))
//False
isinstance(0j, (int, float, complex))
//True
Using user-defined classes
class MyClass:
def __init__(self):
self.name = 'instance'
x = MyClass()
print(isinstance(x, MyClass))