Python issubclass()

Filed Under: Python

Python issubclass() function is used to check if a class is a subclass of another class or not.

Python issubclass()

Python issubclass() function syntax is:


issubclass(class, classinfo)

This function returns True if class is a subclass of classinfo.

A class is considered a subclass of itself. We can also pass a tuple of classes as the classinfo argument, in that case, the function will return True if class is a subclass of any of the classes in the tuple.

Since the object is the base class in Python, the function will return True if classinfo is passed as object class.

Python issubclass() example

Let’s define some classes and subclasses for our example.


class Super:
    pass


class Child(Super):
    pass


class GrandChild(Child):
    pass

Now let’s see the output of issubclass() function with different arguments.


print(issubclass(Child, Super))  # 1st level inheritance
print(issubclass(GrandChild, Super))  # multilevel inheritance
print(issubclass(Child, Child))  # same class
print(issubclass(Super, tuple))  # no inheritance
print(issubclass(Super, object))  # object is the base class

Output:


True
True
True
False
True

Python issubclass() with tuple of classes


print(issubclass(GrandChild, (str, list, Super)))

Output: True

Let’s have a look at another example where we will check if OrderedDict is a subclass of dict or not.


from collections import OrderedDict
print(issubclass(OrderedDict, dict))

Output: True

Python issubclass() vs isinstance()

Python issubclass() and isinstance() functions are very similar, except that former works with classes whereas later works with instance of classes.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages