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

2024-01-12

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

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

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

import constellations

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

我该怎么做?


在模块本身中,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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

运行时将属性注入模块名称空间 的相关文章

随机推荐