Python issubclass function in details

issubclass() function in python :

In python, issubclass() function is used to check if a class is a subclass of another class. The syntax of the function is :

issubclass(B,A)

It will return one boolean value. True if class B is a subclass or derived class of class A, False otherwise. We can also send one tuple as the second argument to this function like below :

issubclas(B,(A,C,D,E)) 

It will check if B is a subclass of A or B is a subclass of C etc.
In this tutorial, we will show you how to use issubclass() function with example.

Check if one class is a subclass of another class :

Let’s try issubclass with one single class. Both of the parameters are one single class. We will create three different classes and test if one class is subclass of another class :

class MainClass:
    pass


class ChildClass(MainClass):
    pass


class GrandChildClass(ChildClass):
    pass


print(issubclass(ChildClass, MainClass))
print(issubclass(GrandChildClass, MainClass))
print(issubclass(GrandChildClass, ChildClass))
print(issubclass(ChildClass, GrandChildClass))
print(issubclass(MainClass, MainClass))

It will print the below output :

True
True
True
False
True

python issubclass

Using issubclass to check one class is the subclass of another tuple of classes :

We can also use issubclass to check one class with another tuple of classes. Like below :

class MainClass:
    pass


class ChildClass(MainClass):
    pass


class GrandChildClass(ChildClass):
    pass


print(issubclass(ChildClass, (MainClass, GrandChildClass)))

It will print the below output :

True

python issubclass
The output is True because ChildClass is a subclass of MainClass. Note that ChildClass is not a subclass of GrandChildClass.
You might also like :

Leave a Reply