我仍然是Python的新手,甚至是酸菜的新手。我有一个带有__getnewargs__()的Vertex(ScatterLayout)类
def __getnewargs__(self):
return (self.pos, self.size, self.idea.text)我的理解是,这将导致pickle从__getnewargs__()而不是对象的字典中pickle对象。
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)组合,并获得了相同的结果。
发布于 2014-09-12 02:06:14
你绝对可以腌制weakref,你也可以腌制dict和list。然而,它们所包含的内容实际上很重要。如果dict或list包含任何不可拾取的项,则酸洗将失败。如果你想要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>发布于 2017-08-09 18:59:38
我通过在__getstate__/__setstate__中的弱/强引用之间切换来解决此问题
class DBObject(object):
def __getstate__(self):
s = self.__dict__.copy()
s['_db'] = s['_db']()
return s
def __setstate__(self, state):
self.__dict__ = state.copy()
self.__dict__['_db'] = weakref.ref(self.__dict__['_db'])https://stackoverflow.com/questions/23644920
复制相似问题