Python issubclass() Function
Returns True if a class is a subclass of the specified class.
Syntax
Python
Copy Code
issubclass(cls, type) issubclass(cls, (type1, type2, ...))
Parameters
Parameter | Description |
---|---|
cls |
Required. The class type to check |
type |
Required. The class type we to check against cls. Either a class or a tuple containing classes must be provided as the second parameter. |
(type1, type2, ...) |
Required.A tuple containing a collection of classes to be checked. Either a class or a tuple containing classes must be provided as the second parameter. |
Example
Python
Copy Code
class Structure: pass class House(Structure): pass class Person: pass print(f'Is a House a Structure? {issubclass(House, Structure)}') print(f'Is a Person a Structure? {issubclass(Person, Structure)}')
Output
Is a House a Structure? True Is a Person a Structure? False
Notes
This works for more than just the immediate parent-child relationship. For example, this tests if the grandchild LittleHouse
is a subclass of the grandparent Structure
:
Example
Python
Copy Code
class Structure: pass class House(Structure): pass class LittleHouse(House): pass print(f'Is a LittleHouse a Structure? {issubclass(LittleHouse, Structure)}')
Output:
Is a LittleHouse a Structure? TrueIf a tuple of classes is provided then the check is performed against each class in the tuple
Example: Checking against a tuple
Python
Copy Code
issubclass(cls, (Type1, Type2, ...))
is the same as
Python
Copy Code
issubclass(cls, Type1) or issubclass(cls, Type2) or ...