Python issubclass() Function
The issubclass()
function in Python is used to check whether a class is a subclass of another class. It returns True
if the first class is a subclass of the second class, or if they are the same class. Otherwise, it returns False
.
The syntax for using the issubclass()
function is as follows:
issubclass(class, classinfo)
Here, class
is the class you want to check, and classinfo
is either a class or a tuple of classes.
Let's see an example to understand how issubclass()
works:
class Vehicle:
pass
class Car(Vehicle):
pass
class Motorcycle(Vehicle):
pass
print(issubclass(Car, Vehicle)) # True
print(issubclass(Motorcycle, Vehicle)) # True
print(issubclass(Vehicle, Car)) # False
In this example, we have a base class called Vehicle
, and two subclasses, Car
and Motorcycle
. When we use issubclass()
to check if Car
and Motorcycle
are subclasses of Vehicle
, it returns True
. However, when we check if Vehicle
is a subclass of Car
, it returns False
because Vehicle
is the base class, and Car
is the subclass.
You can also pass a tuple of classes to classinfo
to check if the first class is a subclass of any of the classes in the tuple. For example:
print(issubclass(Car, (Vehicle, Motorcycle))) # True
print(issubclass(Car, (Motorcycle, int))) # False
In the first case, it returns True
because Car
is a subclass of Vehicle
which is one of the classes in the tuple. In the second case, it returns False
because Car
is not a subclass of Motorcycle
or int
.
Overall, the issubclass()
function is useful when you want to check the inheritance relationship between classes in Python.