I come from a C/C++ background
I would like to subclass dict to make one that automatically opens a JSON file. Here's the code and problem:
class DictFromJSON(dict):
def get_from_file(self, filename):
with open(filename,) as file_reader:
self = json.load(file_reader)
print(self)
def save(self, filename):
with open(filename, "w") as file_writer:
json.dump(self, file_writer)
def __setitem__(self, key, value):
super().__setitem__(key, value)
self.save()
def __init__(self, filename, *args):
super().__init__(args)
self.get_from_file(filename)
json_dict = DictFromJSON("myjson.json")
print(json_dict)
The JSON file for testing contains a single variable mykey
this outputs:
{'mykey': True}
{}
So it's opening the file correctly, print(self) outputs the expected results, but when I print a variable made with the class it's still empty.
I've tried assigning self from json.load() a few different ways, including iterating through keys, but that didn't work either
Assigning to the local name
selfdoes not update the object. You need to useupdate: