像getLogger一样获取对同一对象的引用

2024-06-15 21:10:47 发布

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

我正在用Python开发一个CLI工具。我有一个JSON格式的大结构文件,我通过DataStructure类解析它

完成后,它将在项目中的所有类之间传递该对象。这有点烦人,我想知道是否有人知道如何像logging库那样使用logging.getLogger()引用对象


Tags: 文件工具项目对象jsonclilogging格式
2条回答

只需创建一个名为data的模块,并在其中定义一个返回全局变量的函数。例如,data.py

_impl = None

def get():
    if _impl is None:
        _impl = SomethingThatMakesTheData()
    return _impl

然后你可以在任何你需要的地方import datadata.get()

import json
class DataStructure:

    @classmethod
    def parsinglogic(cls):
        ##Define JSON parsing logic here
        data=json.loads('filename')
        return data

DataStructure.parsinglogic()可用于调用JSON解析器。请参阅,每次调用它时,都会读取JSON文件

而是创建实例方法和实例变量来存储值并将其传递给其他类

import json
class DataStructure:
    def __init__(self,data=None):
        self.data=data

    def parsinglogic(self):
        ##Define JSON parsing logic here
        self.data=json.loads('filename')
        return self.data


d=DataStructure()
data=d.parsinglogic()
#Pass this data to the other classes

相关问题 更多 >