How to check if a class is a subclass or not in Python

In this tutorial, we are going to learn how to check if a class is a subclass or not in Python.

Inheritance is an Object-oriented programming feature that helps a class to inherit the properties of other classes. While debugging any code of multiple lines, we may want to know about the classes and their subclasses.

Python provides us with many built-in methods that make our work easy. We can check whether a class is a subclass of some other class or not using a built-in method known as issubclass().

Python issubclass() method

The issubclass() method tells whether a particular class is a subclass of the given class or not. It takes two parameters namely class and classinfo.

Syntax:
issubclass (class, classinfo)

class – It is the class that is to be checked.
classinfo – It is the class or tuple of classes.

Here, the given class gets checked over the classinfo i.e it checks whether the class is the subclass of classinfo or not. If yes, it returns True. Otherwise, it returns False.

The classinfo can also be the tuple of classes. In this case, if a given class is a subclass of any one of the classes in the tuple it returns True. Otherwise, it returns False.

Python program to check if a class is a subclass or not

class Tree:
    pass

class Wood(Tree):
    pass

class Chair(Wood):
    pass

print("1.",issubclass(Chair, Chair))
print("2.",issubclass(Wood, Tree))  
print("3.",issubclass(Chair, Tree))
print("4.",issubclass(Tree, list))  
print("5.",issubclass(Chair,(Wood,str)))
print("6.",issubclass(Wood,(list,str)))

Output:

1. True
2. True
3. True
4. False
5. True
6. False

In the above code, we have defined three classes Tree, Wood and Chair. Here, the Chair is the subclass of Wood and Wood is the subclass of Tree.
Then we checked whether these classes are subclasses of other classes or not. Each print statement is explained below according to its number:

  1. Every class is a subclass of itself so it returned true.
  2. Wood is a subclass of Tree so it returned true (1st level Inheritance).
  3. Chair is a subclass of Tree so it returned true (Multi-level Inheritance).
  4. Tree is not a subclass of the list so it returned False.
  5. Here Chair is the subclass of one of the classes in the tuple i.e Wood. Hence, it returned True.
  6. Here Wood is not the subclass of any one of the classes in the tuple. So it returned False.

That’s it! Hope you understood the tutorial.

Also, do check our other articles,

Leave a Reply

Your email address will not be published.