首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运行时将属性注入模块命名空间

运行时将属性注入模块命名空间
EN

Stack Overflow用户
提问于 2013-01-31 06:47:41
回答 2查看 1.1K关注 0票数 3

当我正在编写的python模块被导入时,我希望根据同一模块中定义的字典的内容为该模块创建一组属性。以下是该模块中的字典的一小部分:

代码语言:javascript
复制
list_of_constellations = {
   0: Constellation("And", "Andromeda"),
   1: Constellation("Ant", "Antlia"),
   2: Constellation("Aps", "Apus"),
   3: Constellation("Aql", "Aquila"),
}

其中星座是一个命名的元组。我想要的是将一组新的属性注入到名称空间中,其名称是元组中的第一个元素,值是键。因此,在导入后,可以使用以下属性:

代码语言:javascript
复制
import constellations

print constellations.And   # prints 0
print constellations.Ant   # prints 1

我该怎么做呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-31 06:56:33

在模块本身中,globals()函数将模块名称空间作为字典返回;只需使用每个命名元组的第一个元素作为键来设置整数值:

代码语言:javascript
复制
for key, const in list_of_constellations.items():
    globals()[const[0]] = v  # set "And" to 0, etc.

或者从模块外部,使用setattr()将属性添加到模块:

代码语言:javascript
复制
import constellations

for key, const in constellations.list_of_constellations.items():
    setattr(constellations, constellation[0], v)  # set "And" to 0, etc.
票数 3
EN

Stack Overflow用户

发布于 2013-01-31 07:15:35

在Python 2.7中:

代码语言:javascript
复制
>>> import constellations
>>> dir(constellations)
['Constellation', 'list_of_constellations', 'namedtuple', 'namespace', ...]
>>> for key, tupl in constellations.list_of_constellations.iteritems():
>>>    setattr(constellations, tupl[0], key)
>>> dir(constellations)
['And', 'Ant', 'Aps', 'Aql', 'Constellation', 'list_of_constellations',
'namedtuple', 'namespace', ...]

对于Python3,将iteritems()替换为items()

您可以在单独设置属性时使用vars(constellations).update(dict),其中dict是一个字典对象,其中包含要以名称:值格式插入的属性。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14615357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档