Python issubsclass() Function
The issubclass()
function returns True
if the specified object is a subclass of the specified object, otherwise False
.
Syntax
issubclass(class, classinfo)
issubsclass() Parameters
Python issubsclass()
function parameters:
Parameter | Condition | Description |
---|---|---|
class | Required | The class to be checked. |
classinfo | Required | The class, type, or a tuple of classes/types against which the class is checked. |
issubsclass() Return Value
Python issubsclass()
function returns:
True
if class is subclass of a class, or any element of the tupleFalse
otherwise
Examples
Example 1: Checking for Built-in Class Hierarchy with issubclass() function
Let's check for built-int class hierarchy:
print('bool is the subclass of int: ', issubclass(bool, int)) # Output: True
print('float is the subclass of int: ', issubclass(float, int)) # Output: False
output
bool is the subclass of int: True
float is the subclass of int: False
Example 2: Checking for Custom Class Hierarchy
Let's check for Custom Class Hierarchy:
class Person:
pass
class Employee(Person):
pass
class Employer(Person):
pass
print('Employee is a subclass of Person: ', issubclass(Employee, Person)) # Output: True
print('Employer is a subclass of Person: ', issubclass(Employer, Person)) # Output: True
print('Employer is a subclass of Employee: ', issubclass(Employer, Employee)) # Output: False
output
Employee is a subclass of Person: True
Employer is a subclass of Person: True
Employer is a subclass of Employee: False
Example 3: Checking for Multiple Class Hierarchies
Let's check for Multiple Class Hierarchies:
class Polygon:
pass
class Triangle(Polygon):
pass
print('Triangle is a subclass of Polygon: ', issubclass(Triangle, Polygon)) # Output: True
print('Triangle is a subclass of list: ', issubclass(Triangle, list)) # Output: False
print('Triangle is a subclass of list or Polygon: ', issubclass(Triangle, (list, Polygon))) # Output: True
output
Triangle is a subclass of Polygon: True
Triangle is a subclass of list: False
Triangle is a subclass of list or Polygon: True
Example 4: Checking if a Class is a Subclass of Itself
Let's check if a Class is a Subclass of itself:
class MyClass:
pass
print('MyClass is subclass of MyClass: ', issubclass(MyClass, MyClass)) # Output: True
output
MyClass is subclass of MyClass: True