Python is a powerful programming language that provides a wide range of built-in functions to make coding easier and more efficient. One such function is "issubclass()". This function is used to check if a given class is a subclass of another class.
Syntax: The syntax for the issubclass() function is as follows:
|
issubclass(class, classinfo)
|
where:
Example 1:
|
class Shape:
pass
class Rectangle(Shape):
pass
print(issubclass(Rectangle, Shape))
|
In this example, we have created two classes "Shape" and "Rectangle". "Rectangle" is a subclass of "Shape". We then use the issubclass() function to check if "Rectangle" is a subclass of "Shape". The output of this code will be "True".
Output:
|
True
|
|
class Shape:
pass
class Rectangle(Shape):
pass
class Square(Rectangle):
pass
print(issubclass(Square, Shape))
print(issubclass(Square, Rectangle))
|
In this example, we have created three classes "Shape", "Rectangle", and "Square". "Rectangle" is a subclass of "Shape", and "Square" is a subclass of "Rectangle". We then use the issubclass() function to check if "Square" is a subclass of "Shape" or "Rectangle". The output of this code will be "True" for "Shape" and "True" for "Rectangle".
Output:
|
True
True
|
The issubclass() function can also be used to check if a class is a subclass of any class within a tuple of classes. Here is an example:
Example 3:
|
class Dog:
pass
class Cat:
pass
class Bird:
pass
class Parrot(Bird):
pass
print(issubclass(Parrot, (Bird, Cat)))
|
In this example, we have created four classes: "Dog", "Cat", "Bird", and "Parrot". "Parrot" is a subclass of "Bird". We then use the issubclass() function to check if "Parrot" is a subclass of "Bird" or "Cat". The output of this code will be "True" for "Bird" and "False" for "Cat".
Output:
|
True
|