mi código (no pude usar ‘pickle’):
class A(object): def __getstate__(self): print 'www' return 'sss' def __setstate__(self,d): print 'aaaa' import pickle a = A() s = pickle.dumps(a) e = pickle.loads(s) print s,e
impresión :
www aaaa ccopy_reg _reconstructor p0 (c__main__ A p1 c__builtin__ object p2 Ntp3 Rp4 S'sss' p5 b.
Quien me puede decir como usar.
¿Que estás tratando de hacer? Esto funciona para mi:
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
Así que esto se imprimirá:
the original a A:200 a2 - a clone of a before we changed the value A:100
Si necesita establecer estado:
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
que imprime:
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
Eres capaz de pickle
(es decir, este código funciona como debería). Parece que obtienes un resultado, no lo esperas. Si espera el mismo ‘resultado’, intente:
import pickle a = A() s = pickle.dumps(a) e = pickle.loads(s) print s, pickle.dumps(e)
Su ejemplo no es, bueno, un ejemplo típico de “decapado”. Por lo general, los objetos encurtidos se guardan en algún lugar de forma persistente o se envían por cable. Véase, por ejemplo, pickletest.py
: http://www.sthurlow.com/python/lesson10/ .
Hay usos avanzados de pickling
, consulte, por ejemplo, el artículo de serialización de objetos XML de David Mertz: http://www.ibm.com/developerworks/xml/library/x-matters11.html
En pocas palabras, en su ejemplo, e es igual a a.
No tiene que preocuparse por estas cadenas extrañas, puede volcar estas cadenas para guardarlas en cualquier lugar, solo recuerde cuando las cargue, tendrá el objeto ‘a’ nuevamente.