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:
1 2 3 |
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.
1 2 3 4 5 6 7 8 |
class Super: pass class Child(Super): pass class GrandChild(Child): pass |
Now let’s see the output of issubclass() function with different arguments.
1 2 3 4 5 6 7 |
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:
1 2 3 4 5 6 7 |
True True True False True |
Python issubclass() with tuple of classes
1 2 3 |
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.
1 2 3 4 |
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.
Reference: Official Documentation