如何按名称调用模块方法?

时间:2015-07-05 00:30:38

标签: python python-3.x python-3.4

我有一些带有逻辑处理程序的模块

 - handlers
   - __init__.py
   - items.py (with class Items)
   - users.py (with class Users)
 - app.py

在主脚本app.py中,我需要创建Items或Users类的实例并调用一些操作。动态地,通过诸如{ collection: "items", method: "get" }

之类的一些参数
oItems = items.Items()
oItems.get()

我知道如何加载模块中的所有处理程序:from handlers import *,但我不知道如何创建collection类的实例和调用方法。

如果没有动态收集,那就是

method = getattr(items.Items(), 'get')
method()

但是创建一个实例 - 对我来说是一个问题。我正在尝试

 oItems = type('items.Items', (), {})

但它为__main__模块创建了实例,而不是handlers

1 个答案:

答案 0 :(得分:1)

模块只是具有属性的对象。因此,您可以动态检索这些属性:

 collection_module = getattr(handlers, 'items')
 collection_class = getattr(collection_module, 'Items')
 collection = collection_class()

您可以将其存储在字典中以便于查找:

 handlers_mapping = {'items': items.Items, 'users': users.Users}

然后使用handlers_mapping[type_name]()或类似内容。