The isinstance()
function in Python is used to check if an object is an instance of a particular class or any of its subclasses. It returns True
if the object is an instance of the specified class, and False
otherwise.
The syntax for the isinstance()
function is as follows:
isinstance(object, classinfo)
Here, object
is the object that you want to check, and classinfo
can be either a class or a tuple of classes. If object
is an instance of any of the classes specified in classinfo
, the function returns True
. Otherwise, it returns False
.
Here's an example to illustrate the usage of isinstance()
:
class Animal:
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
dog = Dog()
cat = Cat()
print(isinstance(dog, Animal)) # True
print(isinstance(cat, Animal)) # True
print(isinstance(dog, Dog)) # True
print(isinstance(cat, Dog)) # False
print(isinstance(dog, (Dog, Cat))) # True
print(isinstance(cat, (Dog, Cat))) # True
In the above example, we define a base class Animal
and two subclasses Dog
and Cat
. We create instances of Dog
and Cat
classes, and then we use isinstance()
to check their types. The output shows whether the objects are instances of the specified classes or not.