import os
import json
class MagicDict(dict):
"""
dict重载
"""
def __init__(self, config_file=None):
self.config_file = config_file
self.config_dict = {}
if config_file is None:
return None
self.read()
def __getitem__(self, name):
value = None
if self.config_dict == None:
self.read()
try:
value = dict.__getitem__(self.config_dict, name)
except KeyError:
value = self.config_dict[name] = type(self.config_dict)()
return value
def __setitem__(self, name, value):
if self.config_dict == None:
self.read()
self.config_dict[name] = value
def read(self):
"""
read
"""
if self.config_file != None:
with open(self.config_file, 'r') as input_file:
try:
self.config_dict = json.load(input_file)
except:
pass
return self.config_dict
def push(self):
"""
write
"""
if self.config_file != None:
with open(self.config_file, 'w') as output_file:
output_file.write(json.dumps(self.config_dict))
return None
magicdict重写python dict 对文件读写dict
最新推荐文章于 2021-02-19 23:44:45 发布