Skip to main content
 首页 » 编程设计

python之为什么不能 unpickled 这个 set 子类的实例

2024年11月01日9yjmyzz

当我使用 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 

请您参考如下方法:

问题是你没有定义你的类的__init__()方法来接受一个(可选的)可迭代参数,就像它的基类,内置的set类执行,pickle 尝试调用它以在加载文件时恢复实例的内容。

这里有一个简单的方法来解决这个问题:

import pickle 
 
class TreeKeys(set): 
    def __init__(self, iterable=None): 
        if iterable is None: 
            super(TreeKeys, self).__init__() 
        else: 
            super(TreeKeys, self).__init__(iterable) 
 
    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 will now work. 
    print(obj)  # -> TreeKeys([(1, 2, 3)])