Python isinstance() and issubclass() functions

Python isinstance() and issubclass() functions :

Most of us confused with isinstance() and issubclass() functions in python. isinstance() is used to check if an object is an instance of a certain class or any of its subclass. Again, issubclass() is used to check if a class type is subclass of a different class.

isinstance(object, classinfo)
Check if object is an instance of class classinfo or a tuple of classes.

issubclass(class, classinfo)
Check if class is a subclass of another class classinfo or a tuple of classes.

For both cases, the second parameter is a single class or a tuple of classes.

Example of isinstance() and issubclass() :

Let’s try to understand both functions with a simple example :

class MainClass:
    pass


class ChildClass(MainClass):
    pass


class GrandChildClass(ChildClass):
    pass


child = ChildClass()
print(isinstance(child, MainClass))
print(isinstance(child, ChildClass))
print(issubclass(ChildClass, ChildClass))
print(issubclass(ChildClass, MainClass))
print(issubclass(ChildClass, (MainClass, GrandChildClass)))
print(isinstance(child, (MainClass, GrandChildClass)))

It will print the below output :

True
True
True
True
True
True

python isinstance issubclass explanation

Explanation :

Let’s try to understand the above print statements :

1. print(isinstance(child, MainClass)) : child object is an instance of child class of MainClass i.e. ChildClass
2. print(isinstance(child, ChildClass)) : child object is an instance of class ChildClass
3. print(issubclass(ChildClass, ChildClass)) : same ChildClass.
4. print(issubclass(ChildClass, MainClass)) : ChildClass is sub class of MainClass.
5. print(issubclass(ChildClass, (MainClass, GrandChildClass))) : ChildClass is sub class of MainClass. Note that it is not a sub class of GrandChildClass.
6. print(isinstance(child, (MainClass, GrandChildClass))) : child object is an instance of child class of MainClass

You might also like :

Leave a Reply