2017-05-27 23 views
2

我想要找到继承“基类”的模块中的所有类,并且模块由字符串指定。
例如寻找由字符串指定的模块/类

for c in find_classes('robo.extras.contrib') : 
o = c() 
o.process(argv = self.argv[1:]) 

在上述例子中,find_classes看起来通过该继承的类与方法processrobo.extras.contrib所有模块,其实例化和运行的方法。

我一直在寻找python.org,但似乎没有找到答案,如果任何人都可以指向正确的方向,甚至在这里给我一个快速样本,我会很高兴。

谢谢:)

回答

0
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'): 
... 
+0

绝对精彩!我预计它会复杂得多,但是你的代码片段很短并且容易理解。谢谢 :) – Rayne