在没有命名引用的情况下使用 Pickle
我正在尝试腌制一些自定义类,而不参考原始类本身。
我尝试修改原始的 getstate() 函数以仅返回字典。这个解决方案看起来很有效,因为它只返回一个字典对象,但是当我尝试恢复它时,它仍然需要原始类。
这就是我为获取对象的字典所做的事情:
def __getstate__(self):
odict = self.__dict__.copy()
return odict
这是我的保存代码:
utils.save_pickle(self.__getstate__(), self.save_path)
其中 save_pickle 只是:
def save_pickle(obj,name):
with open(name, 'wb') as handle:
pickle.dump(obj, handle, protocol=2)
return
但是,当我尝试取消数据时,pickle 仍然知道这是一个自定义类并使用 setstate() 函数。我怎样才能实现只腌制一本字典而不是对类的引用。
I am trying to pickle some of my custom classes without any reference to the original class itself.
I tried to modify the original getstate() function to just return a dictionary. This solution looks like it works, because its just returns a dictionary object, however when I tried to recover it still requires the original class.
This is what I do for getting the object's dictionary:
def __getstate__(self):
odict = self.__dict__.copy()
return odict
And this is my saving code:
utils.save_pickle(self.__getstate__(), self.save_path)
where save_pickle is just:
def save_pickle(obj,name):
with open(name, 'wb') as handle:
pickle.dump(obj, handle, protocol=2)
return
However when I tried to unpickle the data, pickle still knows that this is a custom class and uses the setstate() function of that class. How can I achieve just to pickle a dictionary and not a reference to class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定我是否正确回答了你的问题。但你总是可以认为类是指令:
Not sure if i got your question right. But you always can think classes are dicts: