我有两个类需要app_config(在我的例子中,app_config应该在我的项目中的所有类中全局可用).

Class1需要app_config,它提供了一些我需要在app_config中再次更新的输入,就像class2中的wise一样.

稍后我需要在类1和类2中更新app_config.

更新实例变量的正确方法是什么.我做的是正确的还是需要不同的考虑?

import requests 
app_config = {
    "MaxThreadCount": 10,
    "BaseURL": "https://google.com",
    "DB": "some db ip"
}

class Class1():
    def __init__(self, app_config):
        self.app_config = app_config
    
    def get_few_more_configs_in_class1(self):
        var1 = requests.get(self.app_config["BaseURL"])
        print("get few data")
        return {"class-1": "some inputs"}

    def set_appconfig(self, app_config):
        self.app_config = app_config

class Class2():
    def __init__(self, app_config):
        self.app_config = app_config
    
    def gather_few_more_configs_in_class2(self, inputs_from_class1):
        print("connect to db")
        return {"db-inputs": "some more inpus"}
    
    def set_appconfig(self, app_config):
        self.app_config = app_config

c1 = Class1(app_config=app_config)
c2 = Class2(app_config=app_config)
class1_inputs = c1.get_few_more_configs_in_class1()
class2_inputs = c2.gather_few_more_configs_in_class2(class1_inputs)
app_config.update(class1_inputs)
app_config.update(class2_inputs)

c1.set_appconfig(app_config=app_config)
c2.set_appconfig(app_config=app_config)

        

推荐答案

以下是一些更有意义的变化:

import requests

app_config = {
    "MaxThreadCount": 10,
    "BaseURL": "https://google.com",
    "DB": "some db ip"
}


class Class1():
    def __init__(self, cfg):  # you want to avoid shadowing something global
        # since you have a setter, discourage direct access
        self._cfg = cfg  

    def get_few_more_configs_in_class1(self):
        var1 = requests.get(self.app_config["BaseURL"])
        print("get few data")
        # no need to update after return, just update directly
        self._cfg.update({"class-1": "some inputs"})
    
    # this is a better way to expose and allow setting, with a property
    @property
    def app_config(self):
        return self._cfg
    
    @app_config.setter
    def app_config(self, cfg):
        self._cfg = cfg


class Class2():
    def __init__(self, cfg):
        self._cfg = cfg

    def gather_few_more_configs_in_class2(self):
        print("connect to db")
        # here, you can use whatever was previously set in your `app_config`
        print("using", self._cfg['class-1'])
        self._cfg.update({"db-inputs": "some more inpus"})

    # this is a better way to expose and allow setting, with a property
    @property
    def app_config(self):
        return self._cfg

    @app_config.setter
    def app_config(self, cfg):
        self._cfg = cfg


c1 = Class1(app_config)
c2 = Class2(app_config)

c1.get_few_more_configs_in_class1()
# no need to pass stuff in, already has the config
c2.gather_few_more_configs_in_class2()  

然而,既然你显然想把你的app_config更多地用作一个共享应用state,那就这么说吧?通常情况下,最好避免使用globals,所以你可以在main()中设置东西.最后,如果您有多个具有相同逻辑的类,为什么不使用继承呢?

import requests


class StateSharing:
    def __init__(self, state: dict):
        self._state = state

    @property
    def state(self) -> dict:
        return self._state

    @state.setter
    def state(self, state: dict):
        self._state = state


class Class1(StateSharing):
    def get_few_more_configs_in_class1(self):
        requests.get(self.state["BaseURL"])
        print("get few data")
        self._state.update({"class-1": "some inputs"})


class Class2(StateSharing):
    def __init__(self, state: dict, something_else: str):
        super().__init__(state)
        self.something_else = something_else

    def gather_few_more_configs_in_class2(self):
        print("connect to db")
        print("using", self._state['class-1'])
        self._state.update({"db-inputs": "some more inpus"})


def main():
    state = {
        "MaxThreadCount": 10,
        "BaseURL": "https://google.com",
        "DB": "some db ip"
    }
    c1 = Class1(state)
    c2 = Class2(state, 'something!')

    c1.get_few_more_configs_in_class1()
    c2.gather_few_more_configs_in_class2()


if __name__ == '__main__':
    main()

Python相关问答推荐

列表上值总和最多为K(以O(log n))的最大元素数

如何使用Jinja语法在HTML中重定向期间传递变量?

即使在可见的情况下也不相互作用

时间序列分解

rame中不兼容的d类型

如何从具有不同len的列表字典中创建摘要表?

在Python Attrs包中,如何在field_Transformer函数中添加字段?

将输入管道传输到正在运行的Python脚本中

Python库:可选地支持numpy类型,而不依赖于numpy

"使用odbc_connect(raw)连接字符串登录失败;可用于pyodbc"

在含噪声的3D点网格中识别4连通点模式

转换为浮点,pandas字符串列,混合千和十进制分隔符

计算天数

如何合并两个列表,并获得每个索引值最高的列表名称?

Django admin Csrf令牌未设置

Geopandas未返回正确的缓冲区(单位:米)

为什么Python内存中的列表大小与文档不匹配?

多个矩阵的张量积

修改.pdb文件中的值并另存为新的

类型对象';敌人';没有属性';损害';