Sometimes, we want to find all the subclasses of a class given its name with Python.
In this article, we’ll look at how to find all the subclasses of a class given its name with Python.
How to find all the subclasses of a class given its name with Python?
To find all the subclasses of a class given its name with Python, we can use the __subclasses__
property.
For instance, we write
class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass
print([cls.__name__ for cls in Foo.__subclasses__()])
to create 4 classes.
Then we get all the subclasses of Foo
with Foo.__subclasses__()
.
And then we get the name of each class with the __name__
property.
Conclusion
To find all the subclasses of a class given its name with Python, we can use the __subclasses__
property.