怎么自己腌制?
我希望我的类实现 Save 和 Load 函数,这些函数只需对类进行 pickle 即可。但显然你不能以下面的方式使用“self”。你怎么能这样做呢?
self = cPickle.load(f)
cPickle.dump(self,f,2)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这就是我最终所做的。更新 __dict__ 意味着我们保留添加到类中的所有新成员变量,并且只更新对象上次 pickle 时存在的成员变量。这似乎是最简单的,同时在类本身内部维护保存和加载代码,因此调用代码只执行 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().转储部分应该按照您的建议工作。对于加载部分,您可以定义一个 @classmethod 从给定文件并返回它。
然后调用者会做类似的事情:
The dump part should work as you suggested. for the loading part, you can define a @classmethod that loads an instance from a given file and returns it.
then the caller would do something like:
如果你想让你的类从保存的pickle中更新自己......你几乎必须使用
__dict__.update
,就像你在自己的答案中一样。然而,这有点像一只猫在追它的尾巴……因为您要求实例本质上“重置”自身为之前的状态。您的答案略有调整。您实际上可以pickle
self
。我使用
loads
和dumps
而不是load
和dump
因为我希望将 pickle 保存到字符串中。使用load
和dump
到文件也可以。而且,实际上,我可以使用 dill 将类实例 pickle 到文件中,以供以后使用……即使该类是交互式定义的。从上面继续...
然后停止并重新启动...
我正在使用
dill
,可在此处使用:https://github.com/uqfoundationIf you want to have your class update itself from a saved pickle… you pretty much have to use
__dict__.update
, as you have in your own answer. It's kind of like a cat chasing it's tail, however… as you are asking the instance to essentially "reset" itself with prior state.There's a slight tweak to your answer. You can actually pickle
self
.I used
loads
anddumps
instead ofload
anddump
because I wanted the pickle to save to a string. Usingload
anddump
to a file also works.And, actually, I can use
dill
to pickle an class instance to a file, for later use… even if the class is defined interactively. Continuing from above...then stopping and restarting...
I'm using
dill
, which is available here: https://github.com/uqfoundation我就是这样做的。优点是不需要创建新对象。您可以直接加载它。
如何使用它:
下面,我用一个完全有效的最小示例更新了答案。这可以根据您自己的需要进行调整。
This is how I did it. The advantage is that you do not need to create a new object. You can just load it directly.
How to use it:
Bellow, I updated the answer with a fully working minimal example. This can be adapted to your own needs.
这里的文档中有一个如何pickle实例的示例。 (向下搜索“TextReader”示例)。这个想法是定义
__getstate__
和__setstate__
方法,它们允许您定义需要腌制的数据,以及如何使用该数据重新实例化对象。There is an example of how to pickle an instance here, in the docs. (Search down for the "TextReader" example). The idea is to define
__getstate__
and__setstate__
methods, which allow you to define what data needs to be pickled, and how to use that data to re-instantiate the object.