How to Find All the Subclasses of a Class? – Finxter

0
30
How to Find All the Subclasses of a Class? – Finxter


Problem Formulation

Given a class by name (string). How to find all the subclasses of the given class?

Example: Here’s an example scenario with a subclass hierarchy.

class Parent:
    pass

class Daughter(Parent):
    pass

class Son(Parent):
    pass

class Grandson(Son):
    pass

Desired outputs: Next, let’s quickly establish what you want to accomplish with two examples.

Given: Son
Result: Grandson


Given: Parent
Result: Daughter, Son

For the most basic cases, we don’t assume a recursive solution requirement, so we don’t consider Grandson also a subclass of Parent.

Solution If We Have the Class Object, Not Only the Class Name

Assume (for now), we have the class object. We’re looking at a slightly more complicated case without this assumption in the next section of this article.

In this case, we can simply get all subclasses of the class using the my_class.__subclasses__() magic method:

class Parent:
    pass

class Daughter(Parent):
    pass

class Son(Parent):
    pass

class Grandson(Son):
    pass


print(Parent.__subclasses__())
# [<class '__main__.Daughter'>, <class '__main__.Son'>]

If you only need a list of all names of subclasses, and not the whole clutter around the output, you can use a list comprehension statement like so:

names = [cls.__name__ for cls in Parent.__subclasses__()]
print(names)
# ['Daughter', 'Son']

Recursive for All Subclasses

Todo: I’ll do it tomorrow, promised! 😉

If We Only Have the String Name of the Class

Todo: I’ll do it tomorrow, promised! 😉



Source link

Leave a reply

Please enter your comment!
Please enter your name here