Python built-in Method - issubclass()

‮.www‬theitroad.com

The issubclass() method in Python is a built-in function that allows you to check whether a class is a subclass of another class. The method returns a boolean value - True if the first class is a subclass of the second class, and False otherwise.

The syntax for issubclass() is as follows:

issubclass(class, classinfo)

Here, class is the class to be checked, and classinfo is either a class object or a tuple of class objects. If class is a subclass of any of the classes specified in classinfo, the method returns True.

For example:

class MyClass:
    pass

class MySubclass(MyClass):
    pass

print(issubclass(MySubclass, MyClass))  # True
print(issubclass(MyClass, MySubclass))  # False

In the example above, we define a class MyClass and a subclass MySubclass. We then use the issubclass() function to check if MySubclass is a subclass of MyClass, and if MyClass is a subclass of MySubclass.

The issubclass() function is useful when you need to check the inheritance relationship between two classes at runtime. It can be used, for example, to implement a generic function that works with objects of different classes that share a common base class.

Note that issubclass() returns True for a class that is a subclass of the second class, as well as for a class that is the same as the second class. Also note that issubclass() only works with classes, and not with instances or built-in types like integers or strings.