Pickling and unpickling inherited attributes

Sam Pointon free.condiments at gmail.com
Sun Oct 30 19:45:13 EST 2005


The reason the state of obj.A and obj.B aren't preserved is because
your __getstate__ and __setstate__ don't preserve them - they only save
obj.C, and you don't make a call to the parent class's respective
methods. Here's what I mean:

>>> import pickle
>>> class Child(Parent):

        __slots__=['C',]
        def __init__(self, c):
                self.C=c
        def __getstate__(self):
                return Parent.__getstate__(self) + (self.C)
        def __setstate__(self, tup):
                self.C = tup.pop()
                Parent.__setstate__(self, tup)

>>> obj = Child('foo')
>>> obj.A = 'bar'
>>> obj.B = 'baz'
>>> objct = pickle.loads(pickle.dumps(obj))
>>> objct.A
'bar'
>>> objct.B
'baz'
>>> objct.C
'foo'




More information about the Python-list mailing list