将一个对象腌制为其父对象 class 的实例?
Pickling an object as an instance of its parent class?
假设我有以下子class,我用它来临时赋予list
一些额外的方法,
class MyList(list):
def some_function(self):
pass
然后我会做类似
的事情
>>> f = MyList()
>>> .. bunch of list stuff ...
>>> cPickle.dump(f,open('somefile','w'))
现在,一切都很好,直到我尝试打开文件
>>> cPickle.load(open('somefile'))
我收到投诉说 MyList
不存在。有什么办法
将 MyList
作为普通的 list
腌制,这样当我稍后尝试加载时
pickle 文件,我没有得到这个 missing class 错误?我希望 pickle 文件只引用内置 list
类型。
我认为您想做的是腌制 class 实例并将 class 描述捆绑在腌制对象中。 pickle
不会腌制 class 描述,但 dill
会。
>>> class MyList(list):
... def some_function(self):
... pass
...
>>> f = MyList()
>>> import dill
>>> dill.dump(f, open('somefile','w'))
>>>
然后加载后,它就可以正常工作了...
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__()
假设我有以下子class,我用它来临时赋予list
一些额外的方法,
class MyList(list):
def some_function(self):
pass
然后我会做类似
的事情>>> f = MyList()
>>> .. bunch of list stuff ...
>>> cPickle.dump(f,open('somefile','w'))
现在,一切都很好,直到我尝试打开文件
>>> cPickle.load(open('somefile'))
我收到投诉说 MyList
不存在。有什么办法
将 MyList
作为普通的 list
腌制,这样当我稍后尝试加载时
pickle 文件,我没有得到这个 missing class 错误?我希望 pickle 文件只引用内置 list
类型。
我认为您想做的是腌制 class 实例并将 class 描述捆绑在腌制对象中。 pickle
不会腌制 class 描述,但 dill
会。
>>> class MyList(list):
... def some_function(self):
... pass
...
>>> f = MyList()
>>> import dill
>>> dill.dump(f, open('somefile','w'))
>>>
然后加载后,它就可以正常工作了...
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__()