Skip to content Skip to sidebar Skip to footer

How To Pickle An Object Of A Class B (having Many Variables) That Inherits From A, That Defines __setstate__ And __getstate__

My problem is: class A(object): def __init__(self): #init def __setstate__(self,state): #A __setstate__ code here def __getstate__(self):

Solution 1:

According to the documentation, when __getstate__ isn't defined, the instance's __dict__ is pickled so maybe, you can use this to define your own state methods as a combination of the A methods and the instance's __dict__:

import pickle

classA(object):
    def__init__(self):
        self.a = 'A state'def__getstate__(self):
        return {'a': self.a}

    def__setstate__(self, state):
        self.a = state['a']

classB(A):
    def__init__(self):
        A.__init__(self)
        self.b = 'B state'def__getstate__(self):
        a_state = A.__getstate__(self)
        b_state = self.__dict__
        return (a_state, b_state)

    def__setstate__(self, state):
        a_state, b_state = state
        self.__dict__ = b_state
        A.__setstate__(self, a_state)

b = pickle.loads(pickle.dumps(B()))
print b.a
print b.b

Solution 2:

The default behavior of Pickle is __getstate__ is not defined is to pickle the contents of the objects __dict__ attribute - that is where the instance attributes are stored.

Therefore it looks like in your case, all you need to do is to make A's get and set state to preserve the values found in self.__dict__ and restore then at __setstate__ - this should preserve the instance variables of all instances of subclasses of A as well.

Post a Comment for "How To Pickle An Object Of A Class B (having Many Variables) That Inherits From A, That Defines __setstate__ And __getstate__"