如何使用“腌" [英] how to use 'pickle'

查看:91
本文介绍了如何使用“腌"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码(我无法使用'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

打印:

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.

推荐答案

您要做什么?它对我有用:

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

因此,它将打印:

the original a
A:200

a2 - a clone of a before we changed the value
A:100

如果需要setstate:

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

打印:

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

这篇关于如何使用“腌"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆