Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: find all classes which inherit from this one? [duplicate]

Is there any way in python to query a namespace for classes which inherit from a particular class? Given a class widget I'd like to be able to call something like inheritors(widget) to get a list of all my different kinds of widget.

like image 989
kdt Avatar asked May 04 '11 10:05

kdt


People also ask

How do you check if a class inherits from another class Python?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.

What is __ Init_subclass __ in Python?

In python __init_subclass__ can be used to implement class registries. In other words, this is keeping track of global or equivalent objects of the subclasses of a class that have been defined so that they can be easily accessed later.

How do you check inheritance in Python?

Two built-in functions isinstance() and issubclass() are used to check inheritances. The function isinstance() returns True if the object is an instance of the class or other classes derived from it. Each and every class in Python inherits from the base class object .

How do you access subclasses in Python?

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. However you find the class, cls.


1 Answers

You want to use Widget.__subclasses__() to get a list of all the subclasses. It only looks for direct subclasses though so if you want all of them you'll have to do a bit more work:

def inheritors(klass):     subclasses = set()     work = [klass]     while work:         parent = work.pop()         for child in parent.__subclasses__():             if child not in subclasses:                 subclasses.add(child)                 work.append(child)     return subclasses 

N.B. If you are using Python 2.x this only works for new-style classes.

like image 53
Duncan Avatar answered Oct 13 '22 16:10

Duncan