how to use 'pickle'

后端 未结 3 1064
谎友^
谎友^ 2020-12-21 16:50

my code(i was unable to use \'pickle\'):

class A(object):
    def __getstate__(self):
        print \'www\'
        return \'sss\'
    def __setstate__(self,         


        
相关标签:
3条回答
  • 2020-12-21 17:34

    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
    
    0 讨论(0)
  • 2020-12-21 17:39

    In a nutshell, in your example, e equals a.

    Don't have to care about these strang strings, you can dumps these strings to save to anywhere, just remember when you loads them, you got 'a' object again.

    0 讨论(0)
  • 2020-12-21 17:42

    You are able to pickle (meaning, this code works as it should). You just seem to get a result, you don't expect. If you expect the same 'output', try:

    import pickle
    a = A()
    s = pickle.dumps(a)
    e = pickle.loads(s)
    print s, pickle.dumps(e)
    

    Your example isn't, well, a typical 'pickling' example. Usually pickled objects are saved somewhere persistently or sent over the wire. See e.g. pickletest.py: http://www.sthurlow.com/python/lesson10/.

    There are advanced uses of pickling, see for example David Mertz XML object serialisation article: http://www.ibm.com/developerworks/xml/library/x-matters11.html

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