腌制链接的对象 [英] Pickle linked objects
本文介绍了腌制链接的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想腌制一个对象和引用第一个的第二个对象.当我天真地腌制/解开两个对象时,引用将成为副本.如何保留两个对象foo
和bar.foo_ref
之间的链接?
I want to pickle an object and a second object that references the first. When I naively pickle/unpickle the two objects, the reference becomes a copy. How do I preserve the link between the two objects foo
and bar.foo_ref
?
import pickle
class Foo(object):
pass
foo = Foo()
bar = Foo()
bar.foo_ref = foo
with open('tmp.pkl', 'wb') as f:
pickle.dump(foo, f)
pickle.dump(bar, f)
with open('tmp.pkl', 'rb') as f:
foo2 = pickle.load(f)
bar2 = pickle.load(f)
print id(foo) == id(bar.foo_ref) # True
print id(foo2) == id(bar2.foo_ref) # False
# want id(foo2) == id(bar2.foo_ref)
推荐答案
我以前的答案没有说明您的意思.代码的问题是您没有使用Pickler
和Unpickler
对象.这是具有多个转储调用的工作版本:
My previous answer was missing your point. The problem with your code is that you're not using the Pickler
and Unpickler
objects. Here's a working version with multiple dump calls:
import pickle
class Foo(object):
pass
foo = Foo()
bar = Foo()
bar.foo_ref = foo
f = open('tmp.pkl', 'wb')
p = pickle.Pickler(f)
p.dump(foo)
p.dump(bar)
f.close()
f = open('tmp.pkl', 'rb')
up = pickle.Unpickler(f)
foo2 = up.load()
bar2 = up.load()
print id(foo) == id(bar.foo_ref) # True
print id(foo2) == id(bar2.foo_ref) # True
这篇关于腌制链接的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文