我正在动态生成类名,然后想通过其名称导入该类来访问静态方法。按名称动态导入静态访问类
这是“the_module.py”导入类:
class ToImport(object):
@classmethod
def initialize(cls, parameter):
print parameter
根据Blog post这是据我走过来:
theModule = __import__("the_module")
toImport = getattr(theModule, "ToImport")
toImport.initialize("parameter")
但博客例子似乎是不完整,因为它给了我一个模块对象,没有我想要的类ToImport
。查看__import__()
documentation显示了该函数有更多可选属性。我成功了
theModule = __import__("the_module", globals(), locals(), ["ToImport"])
为什么我必须给fromlist
属性?我无法导入所有模块属性?
哪个版本的py? – 2009-12-21 14:37:23
使用Python 2.6.2 – desolat 2009-12-21 15:39:38