编程语言
首页 > 编程语言> > Python中的pickling weakref

Python中的pickling weakref

作者:互联网

我仍然是Python的新手,甚至更新的酸洗.我有一个类Vertex(ScatterLayout)与__getnewargs__()

def __getnewargs__(self):
    return (self.pos, self.size, self.idea.text)

我的理解是,这将导致pickle从__getnewargs __()而不是对象的字典中挑选对象.

pickle在以下方法中调用(在不同类MindMapApp(App)中):

def save(self):
    vertices = self.mindmap.get_vertices()
    edges = self.mindmap.get_edges()

    output = open('mindmap.pkl', 'wb')

    #pickle.dump(edges, output, pickle.HIGHEST_PROTOCOL)
    pickle.dump(vertices, output, pickle.HIGHEST_PROTOCOL)

    output.close()

当我调用save()方法时,我收到以下错误:

pickle.PicklingError: Can't pickle <type 'weakref'>: it's not found as __builtin__.weakref

我错过了什么或不理解?我也尝试使用相同的结果实现__getstate __()/ __setstate __(state)组合.

解决方法:

你绝对可以挑选一个弱点,你可以挑选一个字典和一个列表.
然而,实际上它们包含的内容很重要.如果dict或list包含不可推断的intems,那么pickle将失败.如果你想腌制弱点,你必须使用莳萝而不是泡菜.然而,未被删除的弱参数反序列化为死引用.

>>> import dill
>>> import weakref
>>> dill.loads(dill.dumps(weakref.WeakKeyDictionary()))
<WeakKeyDictionary at 4528979192>
>>> dill.loads(dill.dumps(weakref.WeakValueDictionary()))
<WeakValueDictionary at 4528976888>
>>> class _class:
...   def _method(self):
...     pass
... 
>>> _instance = _class()
>>> dill.loads(dill.dumps(weakref.ref(_instance)))
<weakref at 0x10d748940; dead>
>>> dill.loads(dill.dumps(weakref.ref(_class())))
<weakref at 0x10e246a48; dead>
>>> dill.loads(dill.dumps(weakref.proxy(_instance)))
<weakproxy at 0x10e246b50 to NoneType at 0x10d481598>
>>> dill.loads(dill.dumps(weakref.proxy(_class())))
<weakproxy at 0x10e246ba8 to NoneType at 0x10d481598>

标签:python,weak-references,pickle
来源: https://codeday.me/bug/20191008/1870585.html