To check if a class is a subclass in Python, the easiest way is with the issubclass() function.
class Fruit:
pass
class Apple(Fruit):
pass
print(issubclass(Apple,Fruit))
print(issubclass(Fruit,Apple))
#Output:
True
False
When working in Python, the ability to perform certain checks in our program is valuable.
One such check is if you want to check if a class is a subclass in Python.
To check if a class is a subclass in Python, the easiest way is with the issubclass() function.
issubclass() allows you to check if a class is a subclass of another class (or tuple of classes) or not.
issubclass() returns True if the given class is the subclass of given class else it returns False.
Below is a simple example showing you how to check if a class is a subclass or not using Python.
class Fruit:
pass
class Apple(Fruit):
pass
class GrannySmith(Apple):
pass
print(issubclass(Apple,Fruit))
print(issubclass(Fruit,Apple))
print(issubclass(GrannySmith,Apple))
print(issubclass(Apple,GrannySmith))
print(issubclass(Fruit,GrannySmith))
print(issubclass(GrannySmith,Fruit))
#Output:
True
False
True
False
False
True
Hopefully this article has been useful for you to learn how to check if a class is a subclass of another class in Python.