gpt4 book ai didi

python - 酸洗 OrderedDict 派生对象

转载 作者:行者123 更新时间:2023-11-30 23:26:08 26 4
gpt4 key购买 nike

我构建了 collections.OrderedDict 标准类的子类。当我尝试 unpickle 此类的对象时,出现以下错误:

Traceback (most recent call last):
File "pickle.py", line 29, in <module>
print cPickle.load(f)
TypeError: ('__init__() takes exactly 1 argument (2 given)', <class '__main__.ConfiguratorsDict'>, ([['toto', 20]],))

为了理解这种行为的原因,我缩小了 collections.OrderedDict 的主体范围,以获得以下触发上述错误的最少代码。这是:

import cPickle

class OrderedDict(dict):
def __reduce__(self):
items = [[k, self[k]] for k in self]
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
if inst_dict:
return (self.__class__, (items,), inst_dict)

return self.__class__, (items,)

class ConfiguratorsDict(OrderedDict):

def __init__(self):
OrderedDict.__init__(self)

self._myspec = "blabla"

if __name__ == "__main__":

f = open("test.pickle","wb")
c = ConfiguratorsDict()
c["toto"] = 20
cPickle.dump(c,f)
f.close()
f = open("test.pickle","rb")
print cPickle.load(f)
f.close()

此时,我真的不明白那里出了什么问题。我是否对 pickle 机制有什么误解,或者是否存在与 OrderedDict 相关的问题?

非常感谢您的帮助

最佳答案

您没有阅读 __reduce__ 的文档足够仔细:

When a tuple is returned, it must be between two and five elements long. Optional elements can either be omitted, or None can be provided as their value. The contents of this tuple are pickled as normal and used to reconstruct the object at unpickling time. The semantics of each element are:

  • A callable object that will be called to create the initial version of the object. The next element of the tuple will provide arguments for this callable, and later elements provide additional state information that will subsequently be used to fully reconstruct the pickled data.

您将类返回为可调用的,并将 items 作为第二个元素返回,因此 unpickle 尝试将 items 传递给类,从而调用 __init__,但您的 __init__ 不接受任何参数,因此您会收到错误。

您必须更改 __init__ 来接受参数,或者避免将其作为第二个元素,而将其作为一个空元组。

关于python - 酸洗 OrderedDict 派生对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22690729/

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