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.
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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With