一个想法是定义你自己的协议,基于pickle描述的概念。在你的类中定义一个__getstate__
和__setsatte__
实例:
class AClass(object):
def __init__(self, v, z):
self.v = v
self.z = z
self._zdict = dict(zip(self.z, self.z))
def __repr__(self):
return repr({'v': self.v, 'z': self.z, '_zdict': self._zdict})
def __getstate__(self):
return {'v': self.v, 'z': self.z}
def __setstate__(self, state):
self.__dict__.update(state)
self._zdict = dict(zip(self.z, self.z))
然后,您可以像这样定义一个save()
和一个load()
函数:
import importlib
import json
import io
def save(instance, dst_file):
data = {
'module': instance.__class__.__module__,
'class': instance.__class__.__name__,
'state': instance.__getstate__()}
json.dump(data, dst_file)
def load(src_file):
obj = json.load(src_file)
module_name = obj['module']
mod = importlib.import_module(module_name)
cls = getattr(mod, obj['class'])
instance = cls.__new__(cls)
instance.__setstate__(obj['state'])
return instance
简单用法(使用StringIO
此处而不是经典文件):
a_class = AClass(10, [2, 3, 4])
my_file = io.StringIO()
save(a_class, my_file)
print(my_file.getvalue())
# -> {"module": "__main__", "class": "AClass", "state": {"v": 10, "z": [2, 3, 4]}}
my_file = io.StringIO(my_file.getvalue())
instance = load(my_file)
print(repr(instance))
# -> {'v': 10, 'z': [2, 3, 4], '_zdict': {2: 2, 3: 3, 4: 4}}