isinstance(object, classinfo)
The isinstance function takes an object and a class as arguments and returns True if the object is an instance of that class or an instance of a subclass of it.
The second argument (the class) can also be a tuple of classes or a recursive structure of tuples of classes, in which case the boolean True will be returned if the object belongs to any of the classes contained in the structure.
- object: Object to evaluate.
- classinfo: Class name, tuple of class names, or recursive structure of tuples containing class names.
The isinstance function returns a boolean.
We can check if the integer 5 belongs to the int class with the following code:
isinstance(5, int)
True
If we pass the name of the class str (text strings) as the second argument, the function returns False:
isinstance(5, str)
False
The classinfo argument can be a tuple of class names, returning True if the analyzed object belongs to any of them:
isinstance(5, (int, str))
True
isinstance(5, (bool, str))
False
It can also be a recursive tuple structure:
isinstance(5, ((int, str), (float, bool)))
True
isinstance(5, ((complex, str), (float, bool)))
False
We can test the function with a custom class:
class circle:
def __init__(self, radio):
self.radio = radio
c = circle(3)
isinstance(c, circle)
True
If the object is an instance of a subclass of the indicated class, the function also returns True. For example, let's create a subclass of the circle class:
class colored_circle(circle):
def __init__(self, radio, color):
super().__init__(radio)
self.color = color
c_blue = colored_circle(5, "blue")
The variable c_blue is an instance of the newly created subclass, so passing the variable and the name of the subclass to the isinstance function returns the boolean True:
isinstance(c_blue, colored_circle)
True
But passing the variable name to the function and the parent class also returns True:
isinstance(c_blue, circle)
True