【问题标题】:Pickle linked objects part 2Pickle 链接对象第 2 部分
【发布时间】:2014-03-26 11:10:49
【问题描述】:

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

未腌制的对象不一样。我错过了什么吗?

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

【问题讨论】:

  • “未腌制的对象不一样”是什么意思?
  • 加载前的class“里面”class2是一个名为“class1”的class1对象。加载“内部”类后,class2 与加载的 class1 不同。

标签: python class pickle


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多