gpt4 book ai didi

python - 如何 pickle 从字典派生的python对象

转载 作者:行者123 更新时间:2023-11-28 22:02:55 24 4
gpt4 key购买 nike

这是我需要 pickle 的类:

class sdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
__reduce__ = dict.__reduce__

在我看来,__reduce__ 应该负责 pickling,而是:

---------------------------------------------------------------------------
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 没有实现它。您的 __getattr__ 正在使用 "__getstate__" 调用以找到该魔术方法,并返回 None 而不是按应有的方式引发 AttributeError。如果您修复了 __getattr__,pickle 将正常工作。

事实上,为什么您无论如何都返回 None 来缺少属性?这真的是您希望您的对象执行的操作吗?

这是一个例子,说明了你试图做的伪造内置函数的困难。幕后发生了微妙的事情,您将不得不参与其中。

附注:identical question .

关于python - 如何 pickle 从字典派生的python对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10364332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com