如果对父类和子类实例进行pickle,如何在类层次结构中进行最佳pickle / unpickle

时间:2010-08-24 07:30:43

标签: python persistence pickle

假设我有一个A类和一个从A派生的B类。我想挑选/取消类B的实例.A和B都定义__getstate __ / __ setstate__方法(假设A和B是复杂的,这使得必须使用__getstate__和__setstate__)。 B应该如何调用A的__getstate __ / __ setstate__方法?我当前的,但也许不是'正确'的方法:

class A(object):
    def __init__():
        self.value=1
    def __getstate__(self):
        return (self.value)
    def __setstate__(self, state):
        (self.value) = state

class B(A):
    def __init__():
        self.anothervalue=2
    def __getstate__(self):
        return (A.__getstate__(self), self.anothervalue)
    def __setstate__(self, state):
        superstate, self.anothervalue = state
        A.__setstate__(self, superstate)

1 个答案:

答案 0 :(得分:4)

我会使用super(B,self)来获取B的实例来调用A的方法:

import cPickle
class A(object):
    def __init__(self):
        self.value=1
    def __getstate__(self):
        return self.value
    def __setstate__(self, state):
        self.value = state

class B(A):
    def __init__(self):
        super(B,self).__init__()
        self.anothervalue=2
    def __getstate__(self):
        return (super(B,self).__getstate__(), self.anothervalue)
    def __setstate__(self, state):
        superstate, self.anothervalue = state
        super(B,self).__setstate__(superstate)

b=B()
with open('a','w') as f:
    cPickle.dump(b,f)


with open('a','r') as f:
    c=cPickle.load(f)
print(b.value)
print(b.anothervalue)

有关方法解析顺序(MRO)和超级

的详细信息,请参阅this article