2011-08-24 33 views
2

我的问题是类似this one,虽然我想去上一步。动态导入一个模块,并在Python实例化一个类

我解析它调用了一些通过名称操作(不带参数)的配置文件。例如:

"on_click": "action1", "args": {"rate": 1.5} 

动作是Python类,从基Action类继承,并可以采取命名的参数。它们存储在项目的'actions'子目录中,前缀为a_。我希望能够通过简单地删除一个新文件来添加新的操作,而无需更改任何其他文件。项目结构是这样的:

myapp/ 
    actions/ 
     __init__.py 
     baseaction.py 
     a_pretty.py 
     a_ugly.py 
     ... 
    run.py 

所有动作类提供了PerformAction()方法和GetName()方法,这就是配置文件是指。在这个例子中,a_pretty.py定义了一个名为PrettyPrinter的类。在PrettyPrinter上调用GetName()返回“action1”。

我想给PrettyPrinter类添加到与“动作1”的关键一本字典,这样我就可以实例化它的新的实例如下所示:

args = {'rate': the_rate} 
instantiated_action = actions['action1'](**args) 
instantiated_action.PerformAction() 

目前,我有以下几点:

actions = [os.path.splitext(f)[0] for f in os.listdir("actions") 
      if f.startswith("a_") and f.endswith(".py")] 

for a in actions: 

    try: 
     module = __import__("actions.%s" % a, globals(), locals(), fromlist=["*"]) 
     # What goes here? 
    except ImportError: 
     pass 

这是导入操作文件,如果我打印dir(module)我看到的类名称;我只是不知道我下一步应该做什么(或者如果这整个方法是正确的方式去...)。

回答

2

如果一切都在你的module是你应该实例化,尝试这样的类:

一个在行动:

try: 
    module = __import__("actions.%s" % a, globals(), locals(), fromlist=["*"]) 
    # What goes here? 
    # let's try to grab and instanciate objects 
    for item_name in dir(module): 
     try: 
      new_action = getattr(module, item_name)() 
      # here we have a new_action that is the instanciated class, do what you want with ;) 
     except: 
      pass 

except ImportError: 
    pass 
+0

感谢;我没有想过使用'getattr'。 – Rezzie