Python 查找由字符串指定的模块/类
我想查找继承“基类”的模块中的所有类,该模块由字符串指定。Python 查找由字符串指定的模块/类,python,python-module,Python,Python Module,我想查找继承“基类”的模块中的所有类,该模块由字符串指定。 例如 在上面的示例中,find_classes在robo.extras.contrib中查找所有模块,查找使用方法进程继承类的类,实例化该类并运行该方法 我一直在浏览python.org,但似乎没有找到这个问题的答案,如果有人能给我指出正确的方向,甚至给我一个快速的例子,我会非常高兴 谢谢:) 然后: for c in find_classes('robo.extras.contrib', with_method='process'):
例如 在上面的示例中,
find_classes
在robo.extras.contrib
中查找所有模块,查找使用方法进程继承类的类,实例化该类并运行该方法
我一直在浏览python.org,但似乎没有找到这个问题的答案,如果有人能给我指出正确的方向,甚至给我一个快速的例子,我会非常高兴
谢谢:)
然后:
for c in find_classes('robo.extras.contrib', with_method='process'):
...
太棒了!我原以为会复杂得多,但您的代码片段很短,很容易理解。谢谢:)
import inspect, importlib
def find_classes(module, with_method=None):
module = importlib.import_module(module)
return [
c for _, c in inspect.getmembers(module, inspect.isclass)
if not with_method or with_method in dir(c)
]
for c in find_classes('robo.extras.contrib', with_method='process'):
...