我正在尝试做类似this的事情,但我没有得到预期的结果。 这是我的代码
import pickle
def saveclass(objects):
f = file(objects[0].name, 'wb')
for obj in objects:
p = pickle.Pickler(f)
p.dump(obj)
f.close()
def loadclass(name, size):
f = file(name, 'rb')
objlist = []
p = pickle.Unpickler(f)
for obj in range(size):
objlist.append(p.load())
f.close()
return objlist
class class1(object):
def __init__(self, name):
self.name = name
class class2(object):
def __init__(self, name, otherclass):
self.name = name
self.otherclass = otherclass
c1 = class1("class1")
c2 = class2("class2", c1)
print c1.name, ':', c1
print c2.name, ':', c2
print c2.name, 'has', c2.otherclass.name, ':',\
c2.otherclass
print c2.name, "'s 'inside' class is c1:", c2.otherclass == c1
print 'saving classes'
saveclass([c1, c2])
print 'Reloading classes'
clist = loadclass("class1", 2)
c1 = clist[0]
c2 = clist[1]
print c1.name, ':', c1
print c2.name, ':', c2
print c2.name, 'has', c2.otherclass.name, ':', c2.otherclass
print c2.name, "'s 'inside' class is c1:", c2.otherclass == c1
print id(c2.otherclass) == id(c1)
未打开的对象不一样。我错过了什么吗?
如果其他类是其他类的列表,我应该做些不同的事情吗?
答案 0 :(得分:1)
你需要腌制整个"宇宙"在一个pickle.dump
调用中相互关联的对象,以使它们正确地被打开。
这是您执行此操作的代码的一个版本。 (当然universe
可能是一个字典,而不是一个包含两个项目的列表,但你明白了。)
import pickle
class class1(object):
def __init__(self, name):
self.name = name
class class2(object):
def __init__(self, name, otherclass):
self.name = name
self.otherclass = otherclass
def test(c1, c2):
print c1.name, ':', c1
print c2.name, ':', c2
print c2.name, 'has', c2.otherclass.name, ':', c2.otherclass
print c2.name, "'s 'inside' class is c1:", (c2.otherclass is c1)
c1 = class1("class1")
c2 = class2("class2", c1)
test(c1, c2)
universe = [c1, c2]
pickled_universe = pickle.dumps(universe)
c1, c2 = pickle.loads(pickled_universe)
test(c1, c2)
输出:
class1 : <__main__.class1 object at 0x01F6A830>
class2 : <__main__.class2 object at 0x01F6A870>
class2 has class1 : <__main__.class1 object at 0x01F6A830>
class2 's 'inside' class is c1: True
class1 : <__main__.class1 object at 0x01F6A8B0>
class2 : <__main__.class2 object at 0x01F71230>
class2 has class1 : <__main__.class1 object at 0x01F6A8B0>
class2 's 'inside' class is c1: True