动态地按名称导入类以进行静态访问 [英] Dynamically import class by name for static access

查看:74
本文介绍了动态地按名称导入类以进行静态访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am generating class names dynamically and then want to import that class by its name to access a static method.

这是在the_module中导入的类。 py:

This is the class to import in "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 __() 文档告诉我,函数有更多的可选属性。我成功了

But the blog example seems to be incomplete as it gives me a module object without my desired class ToImport. Looking at the __import__() documentation shows me that there are more optional attributes to the function. I succeeded with

theModule = __import__("the_module", globals(), locals(), ["ToImport"])

为什么我必须提供 fromlist 属性?我不能导入所有的模块属性?

Why do I have to give the fromlist attribute? Can't I import all the modules attributes?

推荐答案

p>

I have done exactly what you did and I retrieved the class.

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

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

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

我使用的是Python 2.6.4。你能进一步解释一下,到底什么对你不起作用?

I am using Python 2.6.4. Could you explain further, what exactly doesn't work for you?

这篇关于动态地按名称导入类以进行静态访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆