Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

python - how to use 'pickle'

my code(i was unable to use '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

print :

www
aaaa
ccopy_reg
_reconstructor
p0
(c__main__
A
p1
c__builtin__
object
p2
Ntp3
Rp4
S'sss'
p5
b. <__main__.A object at 0x00B08CF0>

who can tell me how to use.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...