I need a working approach of getting all classes that are inherited from a base class in Python.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
New-style classes (i.e. subclassed from
object, which is the default in Python 3) have a__subclasses__method which returns the subclasses:Here are the names of the subclasses:
Here are the subclasses themselves:
Confirmation that the subclasses do indeed list
Fooas their base:Note if you want subsubclasses, you’ll have to recurse:
Note that if the class definition of a subclass hasn’t been executed yet – for example, if the subclass’s module hasn’t been imported yet – then that subclass doesn’t exist yet, and
__subclasses__won’t find it.You mentioned “given its name”. Since Python classes are first-class objects, you don’t need to use a string with the class’s name in place of the class or anything like that. You can just use the class directly, and you probably should.
If you do have a string representing the name of a class and you want to find that class’s subclasses, then there are two steps: find the class given its name, and then find the subclasses with
__subclasses__as above.How to find the class from the name depends on where you’re expecting to find it. If you’re expecting to find it in the same module as the code that’s trying to locate the class, then
would do the job, or in the unlikely case that you’re expecting to find it in locals,
If the class could be in any module, then your name string should contain the fully-qualified name – something like
'pkg.module.Foo'instead of just'Foo'. Useimportlibto load the class’s module, then retrieve the corresponding attribute:However you find the class,
cls.__subclasses__()would then return a list of its subclasses.