Skip to main content
 首页 » 编程设计

python之在模块命名空间中填充值

2025年05月04日14artech

我有一个 python 模块。

我想在运行时向它填充一些值,我该怎么做。

例如。我有一个 list ,

['A', 'B', 'C']

我正在创建具有这些名称的类,并希望它们像我正常创建它们一样可用

for el in ['A', 'B', 'C']: 
    type(el, (object,), {}) 

请您参考如下方法:

我可以想到几种方法来做到这一点......按照(我认为的)最好到最坏的顺序,我们有:

首先,在当前模块上设置属性

# The first way I had of grabbing the module: 
mod = __import__(__name__, fromlist=['nonempty']) 
 
# From Roger's suggestion: 
import sys 
mod = sys.modules[__name__] 
 
for name in ['A', 'B', 'C']: 
    class_ = type(name, (object, ), {}) 
    setattr(mod, name, class_) 
 
print A, B, C 

其次,设置到当前的全局字典中:

for name in ['A', 'B', 'C']: 
    class_ = type(name, (object, ), {}) 
    globals()[name] = class_ 
 
print A, B, C 

最后,使用 exec (eww):

for name in ['A', 'B', 'C']: 
    class_ = type(name, (object, ), {}) 
    exec "%s = class_" % name 
 
print A, B, C 

我已经在一个独立的脚本(其中 __name__ == "__main__")中测试了所有这三个工作,并作为一个更大的包中的模块进行了测试。

编辑:关于评论中方法 1 与方法 2 的讨论,它们都做完全相同的事情。模块的 namespace 在存储在模块上的字典中定义 (here are the docs)。从模块级别,您可以通过 globals() 获取它,从外部您可以通过属性或模块的 __dict__ 属性访问它。

用于演示的交互式 session :

Python 2.6.4 (r264:75706, Nov  8 2009, 17:35:59)  
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import sys 
>>> mod = sys.modules[__name__] 
>>> mod.__dict__ is globals() 
True