如何使用'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>
谁能告诉我该怎么用。
3 个回答
0
简单来说,在你的例子中,e等于a。
你不需要担心这些奇怪的字符串,你可以把这些字符串保存到任何地方,只要记住,当你加载它们的时候,你又得到了'a'这个对象。
3
你可以使用 pickle
(也就是说,这段代码是正常工作的)。不过,你似乎得到了一个你不太期待的结果。如果你想要相同的“输出”,可以试试:
import pickle
a = A()
s = pickle.dumps(a)
e = pickle.loads(s)
print s, pickle.dumps(e)
你的例子其实不是一个典型的“序列化”例子。通常情况下,序列化的对象会被保存到某个地方,或者通过网络发送出去。你可以看看 pickletest.py
的例子:http://www.sthurlow.com/python/lesson10/。
还有一些更高级的 pickle
用法,比如可以参考 David Mertz 的 XML 对象序列化文章:http://www.ibm.com/developerworks/xml/library/x-matters11.html
4
你想要做什么呢?对我来说,这个是可以正常工作的:
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