python - 如何使用 'pickle'

标签 python pickle

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

谁能告诉我怎么用

最佳答案

你想做什么?它对我有用:

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

如果你需要设置状态:

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

关于python - 如何使用 'pickle',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2019489/

相关文章:

python - 无法 pickle 递归嵌套的defaultdict

python - 单例 python 生成器?或者,pickle 一个 python 生成器?

Python 3 : Pickling and UnPickling class instances returning "no persistent load" error

python - 列表字典到嵌套字典

python - 如何拆分数据框并将其存储在 Excel 文件的多个工作表中

Python检查列表中的两个连续单词是否是另一个列表中的单词

python - pickle Z3 Python 对象

python - 我可以在 Python unittest 中对测试方法和/或测试类进行分组吗

python - Django FileField 未使用 SimpleUploadedFile 对象进行验证

python - 重命名模块后 Unpickling 对象