当我正在编写的python模块被导入时,我希望根据同一模块中定义的字典的内容为该模块创建一组属性。以下是该模块中的字典的一小部分:
list_of_constellations = {
0: Constellation("And", "Andromeda"),
1: Constellation("Ant", "Antlia"),
2: Constellation("Aps", "Apus"),
3: Constellation("Aql", "Aquila"),
}其中星座是一个命名的元组。我想要的是将一组新的属性注入到名称空间中,其名称是元组中的第一个元素,值是键。因此,在导入后,可以使用以下属性:
import constellations
print constellations.And # prints 0
print constellations.Ant # prints 1我该怎么做呢?
发布于 2013-01-31 06:56:33
在模块本身中,globals()函数将模块名称空间作为字典返回;只需使用每个命名元组的第一个元素作为键来设置整数值:
for key, const in list_of_constellations.items():
globals()[const[0]] = v # set "And" to 0, etc.或者从模块外部,使用setattr()将属性添加到模块:
import constellations
for key, const in constellations.list_of_constellations.items():
setattr(constellations, constellation[0], v) # set "And" to 0, etc.发布于 2013-01-31 07:15:35
在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是一个字典对象,其中包含要以名称:值格式插入的属性。
https://stackoverflow.com/questions/14615357
复制相似问题