2010-01-07 61 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