在运行时将属性注入模块namesp

2024-05-23 15:47:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

list_of_constellations = {
   0: Constellation("And", "Andromeda"),
   1: Constellation("Ant", "Antlia"),
   2: Constellation("Aps", "Apus"),
   3: Constellation("Aql", "Aquila"),
}

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

^{pr2}$

我该怎么做?在


Tags: 模块andof名称内容字典属性定义
2条回答

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

for key, const in list_of_constellations.items():
    globals()[const[0]] = v  # set "And" to 0, etc.

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

^{pr2}$

在Python 2.7中:

>>> 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是一个包含要插入到名称:值格式。在

相关问题 更多 >