gpt4 book ai didi

python - Pickle 链接对象第 2 部分

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:13 24 4
gpt4 key购买 nike

我正在尝试做类似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)

unpickled 的对象并不相同。我错过了什么吗?

如果 otherclass 是其他类的列表,我应该做一些不同的事情吗?

最佳答案

您需要在一个 pickle.dump 调用中对相互关联的对象的整个“宇宙”进行 pickle,以便正确地对它们进行 unpickled。

这是执行此操作的代码版本。 (当然,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

关于python - Pickle 链接对象第 2 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22659152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com