2011-08-24 34 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