pickle.loads不会返回相同的数据转储

时间:2014-04-21 18:13:36

标签: python pickle

PolicyModule是我创建的一个类。

当我尝试转储/加载它的实例时,我不会得到相同的数据:

module = PolicyModule(new.name,new.domain,decomposed_module[switch][port])
module.install()
modules[new.name] = module
print 'POLICY TO DUMP'
print modules[new.name].isInstalled()
print modules[new.name].name
print modules[new.name].domain
print modules[new.name].action
print modules[new.name].policy  
print '\n'
msg = pickle.dumps(modules[new.name],-1)
x = pickle.loads(msg)
print 'POLICY LOADED'
print x.isInstalled()
print x.name
print x.domain
print x.action
print x.policy 
print '\n'

这就是印刷品:

POLICY TO DUMP
True
routing
match: ('dstip', 10.0.0.1)
parallel:
    sequential:
        match: ('switch', 2) ('dstip', 10.0.0.2)
        fwd 1
    sequential:
        match: ('switch', 2) ('dstip', 10.0.0.3)
        fwd 2
sequential:
    match: ('dstip', 10.0.0.1)
    parallel:
        sequential:
            match: ('switch', 2) ('dstip', 10.0.0.2)
            fwd 1
        sequential:
            match: ('switch', 2) ('dstip', 10.0.0.3)
            fwd 2

POLICY LOADED
True
routing
match: ('dstip', 10.0.0.1)
drop
identity

注意:match,sequential,fwd和parallel是其他类的实例。

对于每个类,我将 setstate getstate 方法设置如下:

def __getstate__(self):
    odict = self.__dict__.copy() # copy the dict since we change it
    return odict

def __setstate__(self, dict):
    self.__dict__.update(dict)

它认为问题在于:

class sequential(CombinatorPolicy):

def __new__(self, policies=[]):
    if len(policies) == 0:
        return identity
    else:
        rv = super(sequential, self).__new__(sequential, policies)
        rv.__init__(policies)
        return rv

在这里:

class parallel(CombinatorPolicy):

def __new__(self, policies=[]):
    # Hackety hack.
    if len(policies) == 0:
        return drop
    else:
        rv = super(parallel, self).__new__(parallel, policies)
        rv.__init__(policies)
        return rv

因为我总是得到 drop 而不是 parallel 实例,而身份而不是顺序 。 这就像 setdate 方法将空列表传递给 new 方法。

1 个答案:

答案 0 :(得分:0)

我自己找到了解决方案。

我忘了在 parallel sequential 类中定义 getnewargs 方法。

更多信息here