Home / Questions / What is the purpose of the isinstance() function in Python?
Explanatory Question

What is the purpose of the isinstance() function in Python?

👁 265 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

The isinstance() function in Python is used to determine if an object is an instance of a particular class or of a subclass of that class. The function takes two arguments: an object and a class or a tuple of classes. The function returns True if the object is an instance of the class or a subclass of the class, and False otherwise.

Here's an example of using the isinstance() function in Python:


class MyClass:
    pass

obj = MyClass()

if isinstance(obj, MyClass):
    print("obj is an instance of MyClass")
else:
    print("obj is not an instance of MyClass")

In this example, the isinstance() function is used to determine if obj is an instance of the MyClass class. If obj is an instance of MyClass, the message "obj is an instance of MyClass" is printed. Otherwise, the message "obj is not an instance of MyClass" is printed.