如何使用“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>
谁可以告诉我如何使用。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你想做什么?它对我有用:
所以这将打印:
如果您需要 setstate:
打印:
What are you trying to do? It works for me:
So this will print:
If you need setstate:
which prints:
您可以
pickle
(意思是,此代码按其应有的方式工作)。你似乎得到了一个结果,但你没有想到。如果您期望相同的“输出”,请尝试:您的示例不是典型的“pickling”示例。通常,腌制的对象会永久保存在某个地方或通过网络发送。参见例如
pickletest.py
:http://www.sthurlow.com/ python/lesson10/.pickling
有一些高级用法,请参阅 David Mertz XML 对象序列化文章:http://www.ibm.com/developerworks/xml/library/x-matters11.htmlYou 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: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简而言之,在您的示例中,e 等于 a。
不必关心这些奇怪的字符串,您可以转储这些字符串以保存到任何地方,只要记住当您加载它们时,您又得到了“a”对象。
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.