如何处理从外部文件配置多个对象?

2024-09-28 18:45:22 发布

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

我有一个JSON文件,它保存了需要为程序中的对象设置的外部设置。这导致代码看起来像这样:

a_settings = ASettings()
a = A(a_settings, <other dependencies>)
b_settings = BSettings()
b = B(b_settings, <other dependencies>)
c_settings = CSettings()
c = C(c_settings, <other dependencies>)

其中,每个XSettings()从设置文件读取它需要的值,然后X的构造函数从注入其中的x_settings变量访问这些值

我很确定这是实现这一目标的错误方式。如果有的话,有哪些更好的方法

说明:设置文件是必需的,因为它包含需要在外部设置但仍需要加载到程序中的值

编辑:JSON文件如下所示:

{
    "a": {
        "a1": "value1",
        "a2": "value2"
    },
    "b": {
        "b1": "value3",
        "b2": "value4"
    },
    "c": "value5"
}

Tags: 文件对象代码程序json目标settings错误
1条回答
网友
1楼 · 发布于 2024-09-28 18:45:22

settings.json

{
    "a": {
        "a1": "value1",
        "a2": "value2"
    },
    "b": {
        "b1": "value3",
        "b2": "value4"
    },
    "c": "value5"
}

Python代码:

import json

settings = json.load(open("settings.json"))
# {'a': {'a2': 'value2', 'a1': 'value1'}, 'b': {'b2': 'value4', 'b1': 'value3'}}
a = A(settings["a"])
b = B(settings["b"])
c = C(settings["c"])

相关问题 更多 >