Dav*_*xon 7 python weak-references pickle
我仍然是Python的新手,甚至更新的酸洗.我有一个类Vertex(ScatterLayout)有__getnewargs__():
def __getnewargs__(self):
return (self.pos, self.size, self.idea.text)
Run Code Online (Sandbox Code Playgroud)
我的理解是,这会导致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()
Run Code Online (Sandbox Code Playgroud)
当我调用该save()方法时,我收到以下错误:
pickle.PicklingError: Can't pickle <type 'weakref'>: it's not found as __builtin__.weakref
Run Code Online (Sandbox Code Playgroud)
我错过了什么或不理解?我也试过实现__getstate__()/ __setstate__(state)组合,结果相同.
你绝对可以腌制weakref,你可以腌制a dict和a list.然而,实际上它们包含的内容很重要.如果dict或list含有不可摧毁的intems,那么酸洗将失败.如果你想腌制a weakref,你必须使用dill而不是pickle.weakref然而,未被删除的反序列化为死引用.
>>> 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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5730 次 |
| 最近记录: |