2009-12-21 70 views
0

我正在动态生成类名,然后想通过其名称导入该类来访问静态方法。按名称动态导入静态访问类

这是“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属性?我无法导入所有模块属性?

+0

哪个版本的py? – 2009-12-21 14:37:23

+0

使用Python 2.6.2 – desolat 2009-12-21 15:39:38

回答

2

我已经完成了你所做的事情,并且我找到了这门课。

In [1]: theModule = __import__("the_module") 

In [2]: toImport = getattr(theModule, "ToImport") 

In [3]: toImport.initialize("parameter") 
parameter 

我正在使用Python 2.6.4。你能否进一步解释,什么对你没有用?

+1

也适用于我,在Python 2.6.2(Ubuntu)和Python 2.5.1(Mac)上测试过, – 2009-12-21 16:38:18