search

What is the use of the "isinstance" function in Python?

The **isinstance** function in Python is used to check if an object is an instance of a particular class or of a subclass of that class. The syntax is as follows:

isinstance(object, classinfo)

where **object** is the object you want to check, and **classinfo** is the class you want to check against. The function returns **True** if **object** is an instance of the specified class or a subclass of that class, and **False** otherwise.

For example:

>>> class A:
...     pass
...
>>> class B(A):
...     pass
...
>>> obj = B()
>>> isinstance(obj, B)
True
>>> isinstance(obj, A)
True
>>> isinstance(obj, int)
False

In this example, the class **A** is a base class, and the class **B** is a subclass of **A**. The **obj** object is an instance of **B**. The **isinstance** function returns **True** when checking if **obj** is an instance of either **B** or **A**, but **False** when checking if it is an instance of **int**.

Related Questions You Might Be Interested