如何腌制自己? [英] How to pickle yourself?

查看:103
本文介绍了如何腌制自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的班级实现保存和加载功能,这些功能只是对班级进行腌制.但是显然,您不能以以下方式使用自我".你该怎么做?

I want my class to implement Save and Load functions which simply do a pickle of the class. But apparently you cannot use 'self' in the fashion below. How can you do this?

self = cPickle.load(f)

cPickle.dump(self,f,2)

推荐答案

这就是我最终要做的.更新__dict__意味着我们保留我添加到类中的所有新成员变量,而仅更新上次腌制对象时存在的成员变量.在类本身内部维护保存和加载代码时,这似乎是最简单的,因此调用代码仅执行object.save().

This is what I ended up doing. Updating the __dict__ means we keep any new member variables I add to the class and just update the ones that were there when the object was last pickle'd. It seems the simplest while maintaining the saving and loading code inside the class itself so calling code just does an object.save().

def load(self):
    f = open(self.filename, 'rb')
    tmp_dict = cPickle.load(f)
    f.close()          

    self.__dict__.update(tmp_dict) 


def save(self):
    f = open(self.filename, 'wb')
    cPickle.dump(self.__dict__, f, 2)
    f.close()

这篇关于如何腌制自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆