Python built-in Method - isinstance()
The isinstance()
method in Python is a built-in function that allows you to check whether an object is an instance of a particular class or of a subclass of that class. The method returns a boolean value - True
if the object is an instance of the specified class, and False
otherwise.
The syntax for isinstance()
is as follows:
isinstance(object, classinfo)
Here, object
is the object to be checked, and classinfo
is either a class object or a tuple of class objects. If object
is an instance of any of the classes specified in classinfo
, the method returns True
.
For example:
class MyClass: pass class MySubclass(MyClass): pass obj1 = MyClass() obj2 = MySubclass() print(isinstance(obj1, MyClass)) # True print(isinstance(obj2, MyClass)) # True print(isinstance(obj1, MySubclass)) # False print(isinstance(obj2, MySubclass)) # True
In the example above, we define a class MyClass
and a subclass MySubclass
. We create two objects obj1
and obj2
, of MyClass
and MySubclass
types respectively. We then use the isinstance()
function to check if each object is an instance of MyClass
or MySubclass
.
The isinstance()
function is useful when you need to determine the type of an object at runtime, for example, when writing code that can handle different types of objects in a generic way.
Note that isinstance()
returns True
for an object that is an instance of a subclass, as well as for an object that is an instance of the parent class or any of its ancestor classes. Also note that isinstance()
only works with classes and instances, and not with built-in types like integers or strings.