在Python中pickleweakref

我对Python还是很陌生,甚至对酸洗也比较新。我有一个类Vertex(ScatterLayout)__getnewargs__()

def __getnewargs__(self):

return (self.pos, self.size, self.idea.text)

我的理解是,这将使泡菜从对象__getnewargs__()而不是从字典中提取对象。

在以下方法中(在另一个类中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)组合,结果相同。

回答:

你绝对可以泡菜a weakref,泡菜adict和a

list。但是,实际上它们包含的内容很重要。如果dictlist包含不可拾取的intem,则酸洗将失败。如果您想泡菜weakref,就必须使用dill而不是pickleweakref但是,未经挑选的反序列化为无效参考。

>>> 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中pickleweakref 的全部内容, 来源链接: utcz.com/qa/410069.html

回到顶部