Iterate over subclasses of a given class in a given module

前端 未结 4 800

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 20:49

    Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library.

    1. You can avoid the getattr call by using inspect.getmembers()
    2. The try/catch can be avoided by using inspect.isclass()

    With those, you can reduce the whole thing to a single list comprehension if you like:

    def find_subclasses(module, clazz):
        return [
            cls
                for name, cls in inspect.getmembers(module)
                    if inspect.isclass(cls) and issubclass(cls, clazz)
        ]
    

提交回复
热议问题