2010-01-07 34 views
2

我的代码(我无法用 '泡菜'):如何使用 '泡菜'

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> 

谁可以告诉我怎么用。

回答

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 

如果您需要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 
0

简而言之,在你的例子中,e等于a。

不必关心这些绞线,你可以将这些字符串转储到任何地方,只要记住当你加载它们时,你又得到了一个“对象”。

3

您可以通过pickle(意思是说,这段代码正常工作)。你似乎得到了一个结果,你不期望。如果你期望有相同的'输出',请尝试:

import pickle 
a = A() 
s = pickle.dumps(a) 
e = pickle.loads(s) 
print s, pickle.dumps(e) 

你的例子不是典型的“酸洗”例子。通常,腌渍对象被永久保存或通过电线发送。见例如pickletest.pyhttp://www.sthurlow.com/python/lesson10/

还有的pickling高级的应用,例如参见戴维·梅茨XML对象序列化的文章:http://www.ibm.com/developerworks/xml/library/x-matters11.html