How best to sort / scatter in class hierarchies if instances of parent and child classes are pickled

Suppose I have a class A and a class B that is derived from A. I want to parse / disassemble an instance of class B. Both A and B define the __getstate __ / __ setstate__ methods (suppose that A and B are complex, which makes use of __getstate__ and __setstate__) necessary. How should B call the __getstate __ / __ setstate__ methods for A? My current, but maybe not the β€œright” approach:

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) 
+4
source share
1 answer

I would use super(B,self) to get instances of B to call methods 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) 

See this article for more information on Order Resolution Order (MRO) and Super.

+4
source

All Articles