从字符串名称加载Python中的类

时间:2016-02-10 15:45:38

标签: python string class

我有一系列的类名,想要全部检查它们并导入它们。怎么做:

CName='Class_blahblah'
from eval(CName) import *  

这就是我得到的:

 SyntaxError: invalid syntax

确切地说:我在IDE中使用FEA软件运行了几个类,我为它们做了类似的事情:

if 'Class_SetSurfPart' in sys.modules:  
    del sys.modules['Class_SetSurfPart']
    print 'old module Class_SetSurfPart deleted'
    from Class_SetSurfPart import *
    reload(sys.modules['Class_SetSurfPart'])
else:
    from Class_SetSurfPart import *

但我希望将所有类名放在List中,并将其作为循环执行,而不是对所有类执行此操作。

2 个答案:

答案 0 :(得分:0)

sys.modules
的密钥放在如下列表中可能是个好主意:

keys = [key for key in sys.modules]

请记住,每个项目都存储为字符串类型。

#I'm assuming that you've already made a list of the classes you want to be 
#checking for in a list. I'll call that list classes.
for name in classes:
    if name in keys:
        del sys.modules[name]  #remember that this does not delete it permanently.
        print "Old module {} deleted".format(name)
        name = __import__(name)
        reload(name)
    else:
        __import__(name)

答案 1 :(得分:0)

您想要importlib.import_module

bruno@bigb:~/Work/playground/imps$ ls pack/
__init__.py  stuff.py  
bruno@bigb:~/Work/playground/imps$ cat pack/stuff.py
class Foo(object):
    pass
bruno@bigb:~/Work/playground/imps$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
>>> import importlib
>>> module = importlib.import_module("pack.stuff")
>>> module
<module 'pack.stuff' from 'pack/stuff.pyc'>
>>> # now you can either use getattr() or directly refer to `module.Foo`: 
>>> cls = getattr(module, "Foo")
>>> cls
<class 'pack.stuff.Foo'>
>>> module.Foo
<class 'pack.stuff.Foo'>
>>> module.Foo is cls
True