我建立了 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 的范围,以获得以下触发 aformentionned 错误的最小代码。这里是:
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()
在这一点上,我真的不明白那里出了什么问题。我对泡菜机制有什么误解还是与 OrderedDict 相关的问题?
非常感谢你的帮助