我的代码(我无法使用'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>谁能告诉我如何使用。
发布于 2010-01-07 18:29:31
你想做什么?它对我来说很有效:
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:
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发布于 2010-01-07 18:19:01
你可以使用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/。
pickling有一些高级用法,例如,请参阅David Mertz XML对象序列化文章:http://www.ibm.com/developerworks/xml/library/x-matters11.html
发布于 2010-01-07 18:16:59
简而言之,在您的示例中,e等于a。
不必关心这些strang字符串,你可以转储这些字符串以保存到任何地方,只要记住当你加载它们时,你又得到了'a‘对象。
https://stackoverflow.com/questions/2019489
复制相似问题