当我使用pickle模块将类实例转储到文件中时,它是成功的,但是,当我从文件中加载实例时,它失败并引发了TypeError
异常。
我发现,从set派生的所有子类在尝试释放时都会产生一个TypeError
。
class TreeKeys(set):
def __init__(self):
super(TreeKeys, self).__init__()
def add(self, tk):
assert tk.__class__ == tuple
super(TreeKeys, self).add(tk)
if __name__ == '__main__':
a = TreeKeys()
a.add((1,2,3))
with open('tmp.pickle', 'wb') as tmp_fd:
pickle.dump(a, tmp_fd)
with open('tmp.pickle', 'rb') as tmp_fd:
obj = pickle.load(tmp_fd) # this is the code line raise the TypeError exception.
pass
Connected to pydev debugger (build 182.3684.100)
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2\helpers\pydev\pydevd.py", line 1664, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2\helpers\pydev\pydevd.py", line 1658, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2\helpers\pydev\pydevd.py", line 1068, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "G:/pycharm-projects/new_keyinfo/verify_treekeys.py", line 56, in <module>
obj = pickle.load(tmp_fd)
File "C:\Python27_64bit\Lib\pickle.py", line 1384, in load
return Unpickler(file).load()
File "C:\Python27_64bit\Lib\pickle.py", line 864, in load
dispatch[key](self)
File "C:\Python27_64bit\Lib\pickle.py", line 1139, in load_reduce
value = func(*args)
TypeError: __init__() takes exactly 1 argument (2 given)
Process finished with exit code -1
答案 0 :(得分:1)
问题是您没有定义类的__init__()
方法来接受(可选的)可迭代参数,例如其基类,内置set
类却没有,{{1} }尝试使用它调用它,以在实例加载文件时恢复其内容。
这是解决此问题的简单方法:
pickle