issubclass()
The built-in issubclass()
function checks if a given class is a subclass of another class, returning a boolean value True
or False
:
>>> issubclass(int, object)
True
issubclass()
Signature
issubclass(class, classinfo)
Arguments
Argument | Description |
---|---|
class |
The class to check if it’s a subclass. |
classinfo |
A class, tuple of classes, or a union type to check against. |
Return Value
- Returns
True
if the first argument,class
, is a subclass (direct, indirect, or virtual) of the second argumentclassinfo
. - Returns
False
if it’s not a subclass. - Raises a
TypeError
ifclassinfo
isn’t a class, tuple of classes, or union type.
issubclass()
Examples
With float
as a subclass of object
:
>>> issubclass(float, object)
True
With bool
as a subclass of int
:
>>> issubclass(bool, int)
True
With int
not being a subclass of float
:
>>> issubclass(int, float)
False
issubclass()
Common Use Cases
The most common use cases for the issubclass()
function include:
- Checking class hierarchies and inheritance relationships
- Verifying if a class implements a particular interface or abstract base class
- Validating input types in functions and methods that accept class objects
issubclass()
Real-World Example
Say that you’re designing a plugin system where each plugin must inherit from a PluginBase
class. You can use issubclass()
to ensure each plugin class correctly inherits from PluginBase
:
>>> class PluginBase:
... pass
...
>>> class PluginA(PluginBase):
... pass
...
>>> class PluginB:
... pass
...
>>> def validate_plugin(plugin_class):
... if issubclass(plugin_class, PluginBase):
... print(f"{plugin_class.__name__} is a valid plugin.")
... else:
... print(f"{plugin_class.__name__} is NOT a valid plugin.")
...
>>> validate_plugin(PluginA)
PluginA is a valid plugin.
>>> validate_plugin(PluginB)
PluginB is NOT a valid plugin.
In this example, issubclass()
helps ensure that only classes inheriting from PluginBase
are considered valid plugins.
Related Resources
Tutorial
Object-Oriented Programming (OOP) in Python
In this tutorial, you'll learn all about object-oriented programming (OOP) in Python. You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see how to instantiate an object from a class.
For additional information on related topics, take a look at the following resources:
- Basic Data Types in Python: A Quick Exploration (Tutorial)
- Duck Typing in Python: Writing Flexible and Decoupled Code (Tutorial)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Exploring Basic Data Types in Python (Course)
- Basic Data Types in Python: A Quick Exploration (Quiz)