Iterate over subclasses of a given class in a given module

前端 未结 4 810

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条回答
  •  旧时难觅i
    2020-12-15 21:12

    Here's one way to do it:

    import inspect
    
    def get_subclasses(mod, cls):
        """Yield the classes in module ``mod`` that inherit from ``cls``"""
        for name, obj in inspect.getmembers(mod):
            if hasattr(obj, "__bases__") and cls in obj.__bases__:
                yield obj
    

提交回复
热议问题