How to Find All the Subclasses of a Class Given its Name?
In this article, we will learn to how to find all subclasses of a class given its name in Python. We will look at the methodology, syntax, keywords, associated terms with some simple approaches, and some custom codes as well to better understand the topic of the class. Let's first have a quick look over what is a class and a subclass in Python.
What is a Class?
Python is a popular scripting language. It also supports the object-oriented programming paradigm concepts. Object-Oriented Programming in Python involves object creation through Class
, Inheritance
, Polymorphism,
and Encapsulation
. A class is like a blueprint that bundles different types of items under one roof. Python can have multiple classes in one Python script. Each class contains its own attributes, instances, and methods to maintain the state of the class. Python classes have the ability to protect the data from outside threats. Classes are accessed from an entity called objects
. It has methods called member functions
to modify the state of the class. Assume your class to be a house that contains house details like room, kitchen, doors, etc. Likewise, Class has different attributes called data members
that tell us about the class.
What is Subclass?
A class that is derived from another class is known as a subclass. This is a concept of inheritance in Python. The subclass derives or inherits the properties of another class.
Find all the Subclasses of a Class Given its Name
Since Python classes are first-class objects, "given its name" signifies that you do not need to use a string with the class's name in place of the class. You can just use the class directly. New-style classes i.e. subclassed from an object, which is the default in Python 3 have a __subclasses__
method. This method returns the subclasses of the class.
Note: If the class definition of a subclass has not been executed yet, for example, if the subclass's module has not been imported yet, then that subclass doesn't exist yet, and __subclasses__
won't find it.
Example: General Method to Find Subclasses
Look at the below code snippet, there are three self-explanatory print statements. This code snippet has one base class my_class and three subclasses A, B, C. The first print statement prints all the names of the subclasses using __subclassess__
method. The second print statement prints the subclasses itself rather than their names. Next, we use for loop and confirm from the output that A, B, C are the subclasses of the main class my_class.
class my_class(object):
pass
class A(my_class):
pass
class B(my_class):
pass
class C(my_class):
pass
#Here are the names of the subclasses:
print([cls.__name__ for cls in my_class.__subclasses__()])
#Here are the subclasses themselves:
print(my_class.__subclasses__())
#Confirmation that my_class is the base class:
for cls in my_class.__subclasses__():
print(cls.__base__)
['A', 'B', 'C']
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C>]
<class '__main__.my_class'>
<class '__main__.my_class'>
<class '__main__.my_class'>
Example: Recursive Method to Find Subclasses
This is a simple, readable function that recursively finds all subclasses of a given class.
class my_class(object):
pass
class A(my_class):
pass
class B(my_class):
pass
class C(my_class):
pass
def get_all_subclasses(cls):
all_subclasses = []
for subclass in cls.__subclasses__():
all_subclasses.append(subclass)
all_subclasses.extend(get_all_subclasses(subclass))
return all_subclasses
#pass base class as argument
print(get_all_subclasses(my_class))
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>]
Example: Find Subclasses using itertools Module
This example is a much shorter version for getting a list of all subclasses. It imports chain
from itertools
module in Python.
class my_class(object):
pass
class A(my_class):
pass
class B(my_class):
pass
class C(my_class):
pass
from itertools import chain
def get_all_subclasses(cls):
return list(
chain.from_iterable(
[list(chain.from_iterable([[x], get_all_subclasses(x)])) for x in cls.__subclasses__()]
)
)
print(get_all_subclasses(my_class))
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>]
Conclusion
In this article, we learned to find all the subclasses of the classes given their name using __subclassess__ method. We discussed three different examples of finding subclasses. We find subclasses using itertools chain module, we used the recursive method to get the list of all subclasses and a general method as well.