Pickling and unpickling inherited attributes

Sam Pointon free.condiments at gmail.com
Mon Oct 31 01:45:13 CET 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):

        def __init__(self, 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
>>> objct.B
>>> objct.C

More information about the Python-list mailing list