【发布时间】:2021-04-03 16:21:48
【问题描述】:
我正在编写一个充当字典的类,但每次进行修改以确保同步状态时,将其内容保存到 json 文件中。
但是,我偶然发现了一种破坏同步的特殊情况:将值附加到字典内的列表时。
由于这里使用__getitem__,我如何确保如果返回的项目被修改,我将其保存到 JSON 文件中?
这是一个功能齐全的代码 sn-p (Python 3.9.2) 来说明我的意思
import json
class SyncDictJSON(dict):
__instances: dict = {}
@classmethod
def create(cls, filepath: str, **kwargs):
if filepath not in SyncDictJSON.__instances:
SyncDictJSON.__instances[filepath] = cls(filepath, **kwargs)
return SyncDictJSON.__instances[filepath]
def __init__(self, filepath: str, **kwargs):
super().__init__(**kwargs)
self.filepath = filepath
self.update(SyncDictJSON.read_data_from_filename(self.filepath))
def __getitem__(self, item):
print(f"getitem {item}")
return super(SyncDictJSON, self).__getitem__(item)
def __setitem__(self, key, value):
print(f"set item {key},{value}")
super().__setitem__(key, value)
SyncDictJSON.write_data_to_filename(self, self.filepath)
def __delitem__(self, key):
super().__delitem__(key)
SyncDictJSON.write_data_to_filename(self, self.filepath)
@staticmethod
def write_data_to_filename(data, filepath: str):
with open(filepath, "w", encoding="utf-8") as file:
json.dump(data, file, indent=2, ensure_ascii=False)
@staticmethod
def read_data_from_filename(filename: str):
with open(filename, "r", encoding="utf-8") as file:
return json.load(file)
@classmethod
def from_file(cls, filepath):
return cls(filepath)
if __name__ == '__main__':
with open("testing.json", "w") as file:
file.write("{}")
dico = SyncDictJSON.create("testing.json")
dico["a_list"] = []
dico["a_list"].append(5)
print(dico) # {'a_list': [5]} but testing.json will be empty
【问题讨论】:
-
我很好奇是否有一种聪明的方法可以实现这一点,但是您无法随时控制某人更改列表对象,该列表对象也恰好被引用为容器中的值.如果一个可变对象存储在您的容器中,也许您可以捕捉到,您可以为它配备一些通知容器类的事件机制(递归地,如果可变对象本身包含可变对象,如列表列表)。
-
您的代码无法与 mw 一起使用(不知道为什么)随机更改会产生正确的输出,但不知道如何。
-
不过还是试试 dico["a_list"] = 5 看看是否可行
-
@pipo1980 对我来说,这段代码以退出代码 0 结束。 dico["a_list"] = 5 将起作用,但问题是我希望更改字典中的对象以触发保存。如果有人想要挑战,你上面的评论似乎是一个好的开始
-
对我来说 dico["a_list"] = 5 作品。我的意思是我有一个空键的 json 文件,其中填充了 dico["a_list"] = 5,问题是你的工作代码不起作用并给出 FileNotFoundError: [Errno 2] No such file or directory: 'testing.json'如果没有文件或 JSONDecodeError: Expecting value error if no file is present or JSONDecodeError: Expecting value error if no file is present or JSONDecodeError: Expecting value error if no file is present or JSONDecodeError: error if no file is present or JSONDecodeError: error if no file is present or JSONDecodeError: Error if no file is present or JSONDecodeError: Error if no file is present 错误,因此如果您不向我们提供我们无法测试您的代码的起始 json 文件,则“功能齐全的代码 sn-p”将不起作用
标签: python json python-3.x