How to find all the subclasses of a class given its name?

后端 未结 10 1802
遥遥无期
遥遥无期 2020-11-22 10:14

I need a working approach of getting all classes that are inherited from a base class in Python.

10条回答
  •  Happy的楠姐
    2020-11-22 10:53

    How can I find all subclasses of a class given its name?

    We can certainly easily do this given access to the object itself, yes.

    Simply given its name is a poor idea, as there can be multiple classes of the same name, even defined in the same module.

    I created an implementation for another answer, and since it answers this question and it's a little more elegant than the other solutions here, here it is:

    def get_subclasses(cls):
        """returns all subclasses of argument, cls"""
        if issubclass(cls, type):
            subclasses = cls.__subclasses__(cls)
        else:
            subclasses = cls.__subclasses__()
        for subclass in subclasses:
            subclasses.extend(get_subclasses(subclass))
        return subclasses
    

    Usage:

    >>> import pprint
    >>> list_of_classes = get_subclasses(int)
    >>> pprint.pprint(list_of_classes)
    [,
     ,
     ,
     ,
     ,
     ,
     ,
     ,
     ]
    

提交回复
热议问题