这是我需要 pickle 的类(class):
class sdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
__reduce__ = dict.__reduce__
在我看来,__reduce__
应该负责 pickle ,但相反:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/daniyar/work/Apr24/<ipython-input-28-1cc94b920737> in <module>()
----> 1 pickle.dumps(sdict(a=1))
/usr/lib/python2.6/pickle.pyc in dumps(obj, protocol)
1364 def dumps(obj, protocol=None):
1365 file = StringIO()
-> 1366 Pickler(file, protocol).dump(obj)
1367 return file.getvalue()
1368
/usr/lib/python2.6/pickle.pyc in dump(self, obj)
222 if self.proto >= 2:
223 self.write(PROTO + chr(self.proto))
--> 224 self.save(obj)
225 self.write(STOP)
226
/usr/lib/python2.6/pickle.pyc in save(self, obj)
304 reduce = getattr(obj, "__reduce_ex__", None)
305 if reduce:
--> 306 rv = reduce(self.proto)
307 else:
308 reduce = getattr(obj, "__reduce__", None)
/usr/lib/python2.6/copy_reg.pyc in _reduce_ex(self, proto)
82 dict = None
83 else:
---> 84 dict = getstate()
85 if dict:
86 return _reconstructor, args, dict
TypeError: 'NoneType' object is not callable
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (171, 0))
我也应该定义__getstate__
吗?我完全迷失了所有这些可用于自定义 pickle 的多种方法:__getinitargs__
、__getstate__
、__reduce__
等...
Google 仅向我推荐了我觉得非常不清楚的官方 pickle 文档。有人可以为我澄清这一点或给我指出一个好的 pickle 教程吗?
最佳答案
我怀疑你是否正走在一条好的道路上。
但是,要解决 pickle 问题:
class sdict(dict):
def __getattr__(self, attr):
if attr.startswith('__'):
raise AttributeError
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
Pickle 试图从你的对象获取状态,而 dict 没有实现它。正在使用 "__getstate__"
调用您的 __getattr__
来查找该魔术方法,并返回 None 而不是按其应有的方式引发 AttributeError
。如果您修复了 __getattr__
,pickle 就能正常工作。
事实上,为什么您要因缺少属性而返回 None 呢?这真的是您希望您的对象执行的操作吗?
这是一个说明您尝试伪造内置函数的困难的示例。幕后正在发生一些微妙的事情,你必须参与其中。
PS:一个identical question .
关于python - 如何pickle从dict派生的python对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10364332/