Python, override__getstate__() and __setstate__()

后端 未结 1 1684
粉色の甜心
粉色の甜心 2021-01-31 11:04

I have these classes:

class Family(object):
    __slot__ = [\'father\', \'var1\']
    def __init__(self, father, var1 = 1):
        self.father, self.var1 = fath         


        
1条回答
  •  北海茫月
    2021-01-31 11:40

    __getstate__ should return a picklable object (such as a tuple) with enough information to reconstruct the instance.

    __setstate__ should expect to receive the same object, and use it to reconfigure the instance.

    For example:

    import cPickle as pickle
    
    class Family(object):
        __slots__ = ['father', 'var1']
        def __init__(self, father, var1 = 1):
            self.father, self.var1 = father, var1
        def __getstate__(self):
            return self.father, self.var1
        def __setstate__(self, state):
            self.father, self.var1 = state
    
    foo = Family('father',1)
    foo.var1 = 2
    foo_pickled = pickle.dumps(foo)
    foo2 = pickle.loads(foo_pickled)
    print(repr(foo2))
    # <__main__.Family object at 0xb77037ec>
    
    print(foo2.var1)
    # 2
    

    0 讨论(0)
提交回复
热议问题