gpt4 book ai didi

python - 从类的构造函数中 unpickle 时出错

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

我想实现一个类(最好是单例),在初始化阶段应使用 cPickle 机制恢复其状态。为此,我编写了以下代码片段:

import cPickle
import collections

class Test(collections.OrderedDict):

path = "test.cp"

def __init__(self):

self.path = "test.cp"

collections.OrderedDict.__init__(self)
try:
f = open(Test.path,"rb")
except IOError:
return
else:
ud = cPickle.load(f)
self.update(ud)
f.close()

def save(self):

f = open(Test.path,"wb")
cPickle.dump(self,f)
f.close()

if __name__ == "__main__":
t = Test()
t.save()
t1 = Test()

运行该代码片段会产生以下错误:

    Traceback (most recent call last):
File "C:\Documents and Settings\pellegrini\Bureau\test.py", line 31, in <module>
t1 = Test()
File "C:\Documents and Settings\pellegrini\Bureau\test.py", line 18, in __init__
ud = cPickle.load(f)
TypeError: ('__init__() takes exactly 1 argument (2 given)', <class '__main__.Test'>, ([],))

当继承 dict 时而不是collections.OrderedDict这有效。从其他类似的帖子来看,这可能与__reduce__有关。方法,但我不明白为什么以及如何?

您知道如何解决这个问题吗?

非常感谢

埃里克

最佳答案

我猜 OrderedDict 有它自己的序列化方式。

def __init__(self, *args):

self.path = "test.cp"

collections.OrderedDict.__init__(self, *args)

试试这个,你会遇到递归问题,因为 pickle 使用 __init__

一个无错误的解决方案是:

import cPickle
import collections

class Test(collections.OrderedDict):

path = "test.cp"

def __init__(self, *args):

self.path = "test.cp"

collections.OrderedDict.__init__(self, *args)
if not args:
try:
f = open(Test.path,"rb")
except IOError:
return
else:
ud = cPickle.load(f)
self.update(ud)
f.close()

def save(self):

with open(Test.path,"wb") as f:
cPickle.dump(self,f)

if __name__ == "__main__":
t = Test()
t.save()
t1 = Test()

单例

import pickle
import collections

_Test_singleton = None

class Test(collections.OrderedDict):

path = "test.cp"

def __new__(self, *args, **kw):
global _Test_singleton
if _Test_singleton is not None:
return _Test_singleton
_Test_singleton = collections.OrderedDict.__new__(self, *args, **kw)
_Test_singleton.load()
return _Test_singleton

def __init__(self, *args):
collections.OrderedDict.__init__(self, *args)

def load(self):
try:
f = open(self.path,"rb")
except IOError:
return
else:
try:
ud = pickle.load(f)
finally:
f.close()
self.update(ud)

def save(self):
with open(self.path,"wb") as f:
pickle.dump(self,f)


if __name__ == "__main__":
t = Test()
t.save()
t1 = Test()
assert t is t1

关于python - 从类的构造函数中 unpickle 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21995387/

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