[英]Pickling an object as an instance of its parent class?
Suppose I had the following subclass that I'm using to temporarily endow list
with some extra methods, 假设我使用以下子类来临时赋予
list
一些其他方法,
class MyList(list):
def some_function(self):
pass
and then I do something like 然后我做类似的事情
>>> f = MyList()
>>> .. bunch of list stuff ...
>>> cPickle.dump(f,open('somefile','w'))
Now, that is all well and good until I try to open the file 现在,一切都很好,直到我尝试打开文件
>>> cPickle.load(open('somefile'))
and I get a complaint that MyList
doesn't exist. 我抱怨
MyList
不存在。 Is there a way to somehow get MyList
to pickle as a plain list
so that when I later try to load the pickle file, I don't get this missing class error? 有没有办法以某种方式将
MyList
腌制为纯list
以便以后我尝试加载腌制文件时,不会出现此遗漏的类错误? I would like the pickle file to only refer to the built-in list
type. 我希望pickle文件仅引用内置
list
类型。
I think what you wanted to do is to pickle the class instance and bundle up the class description in the pickled object. 我认为您想要做的是腌制该类实例并将该类描述捆绑在腌制的对象中。
pickle
doesn't pickle a class description, but dill
does. pickle
不会腌制类描述,但dill
会腌制。
>>> class MyList(list):
... def some_function(self):
... pass
...
>>> f = MyList()
>>> import dill
>>> dill.dump(f, open('somefile','w'))
>>>
And then upon loading, it just works... 然后加载后就可以了...
dude@hilbert>$ python
Python 2.7.12 (default, Jun 29 2016, 12:42:34)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> f = dill.load(open('somefile','r'))
>>> f
[]
>>> type(f)
<class '__main__.MyList'>
>>> g = f.__class__()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.