Use the issubclass()
Function
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Person):
def __init__(self, name, age, school):
super().__init__(name, age)
self.school = school
#Check whethe a class is a subclass of another
print(issubclass(Student, Person))
The issubclass()
function checks whether a certain class is a subclass of another class. A class is considered a subclass of another if it inherits the properties and methods from the parent class whether directly or indirectly. A subclass may also define its own unique properties and methods that are not available to the parent class.
issubclass(cls, parent)
cls |
Required. The class object to be tested. |
parent |
Required. The class object that "cls" is being tested whether it is a subclass of. |
The issubclass()
function returns True
if cls
is a subclass of the parent
, otherwise it returns False.
With Builtin classes
print(issubclass(int, object))
print(issubclass(bool, int))
print(issubclass(bool, str))
Remember that all classes in Python ultimately inherit from the object
class, this is why the issubclass(int, object)
evaluates to True
. The function also confirms that the bool
class is a subclass of the int
and not a subclass of the str
class.
With custom classes
class Vehicle:
def __init__(self, name):
self.name = name
class Car(Vehicle):
def __init__(self, name, color):
super().__init__(name)
self.color = color
class MiniCar(Car):
def __init__(self, name, color):
super.__init__(self, name, color)
print(issubclass(Car, Vehicle)) #direct
print(issubclass(MiniCar, Vehicle)) #indirect