Iterate over subclasses of a given class in a given module

前端 未结 4 809

In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?

4条回答
  •  孤城傲影
    2020-12-15 20:52

    Can I suggest that neither of the answers from Chris AtLee and zacherates fulfill the requirements? I think this modification to zacerates answer is better:

    def find_subclasses(module, clazz):
        for name in dir(module):
            o = getattr(module, name)
            try:
                if (o != clazz) and issubclass(o, clazz):
                    yield name, o
            except TypeError: pass
    

    The reason I disagree with the given answers is that the first does not produce classes that are a distant subclass of the given class, and the second includes the given class.

提交回复
热议问题