What are you trying to do? It works for me:
class A(object):
def __init__(self):
self.val = 100
def __str__(self):
"""What a looks like if your print it"""
return 'A:'+str(self.val)
import pickle
a = A()
a_pickled = pickle.dumps(a)
a.val = 200
a2 = pickle.loads(a_pickled)
print 'the original a'
print a
print # newline
print 'a2 - a clone of a before we changed the value'
print a2
print
print 'Why are you trying to use __setstate__, not __init__?'
print
So this will print:
the original a
A:200
a2 - a clone of a before we changed the value
A:100
If you need setstate:
class B(object):
def __init__(self):
print 'Perhaps __init__ must not happen twice?'
print
self.val = 100
def __str__(self):
"""What a looks like if your print it"""
return 'B:'+str(self.val)
def __getstate__(self):
return self.val
def __setstate__(self,val):
self.val = val
b = B()
b_pickled = pickle.dumps(b)
b.val = 200
b2 = pickle.loads(b_pickled)
print 'the original b'
print b
print # newline
print 'b2 - b clone of b before we changed the value'
print b2
which prints:
Why are you trying to use __setstate__, not __init__?
Perhaps __init__ must not happen twice?
the original b
B:200
b2 - b clone of b before we changed the value
B:100
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…