在Python中动态导入模块并实例化类
我的问题与类似,不过我想再进一步 我正在解析一个配置文件,该文件按名称调用许多操作(带有参数)。例如:在Python中动态导入模块并实例化类,python,parsing,import,Python,Parsing,Import,我的问题与类似,不过我想再进一步 我正在解析一个配置文件,该文件按名称调用许多操作(带有参数)。例如: "on_click": "action1", "args": {"rate": 1.5} 动作是python类,继承自一个基本的Action类,可以采用命名参数。它们存储在项目的“actions”子目录中,前缀为a_uu。我希望能够添加新的操作,只需在那里删除一个新文件,而不必更改任何其他文件。项目结构如下: myapp/ actions/ __init__.py
"on_click": "action1", "args": {"rate": 1.5}
动作是python类,继承自一个基本的Action
类,可以采用命名参数。它们存储在项目的“actions”子目录中,前缀为a_uu
。我希望能够添加新的操作,只需在那里删除一个新文件,而不必更改任何其他文件。项目结构如下:
myapp/
actions/
__init__.py
baseaction.py
a_pretty.py
a_ugly.py
...
run.py
所有操作类都提供一个PerformAction()
方法和一个GetName()
方法,这就是配置文件所引用的方法。在本例中,a_pretty.py
定义了一个名为PrettyPrinter
的类。在PrettyPrinter
上调用GetName()
将返回“action1”
我想将PrettyPrinter
类添加到一个以“action1”为键的字典中,这样我就可以实例化它的新实例,如下所示:
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
目前,我有以下几点:
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)
我会看到类名;我只是不知道下一步该做什么(或者整个方法是否正确……) 如果模块中的所有内容都是您应该实例化的类,请尝试以下操作:
对于正在运行的应用程序:
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
谢谢我没有想到使用getattr
。