Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中动态导入模块并实例化类_Python_Parsing_Import - Fatal编程技术网

在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