Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用';泡菜';_Python_Pickle - Fatal编程技术网

Python 如何使用';泡菜';

Python 如何使用';泡菜';,python,pickle,Python,Pickle,我的代码(我无法使用“pickle”): 打印: 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> www aaaa ccopy_注册 _重建器 p0 (c___)主要__ A. p1 c__内置__ 对象 p2 Ntp3 Rp4 S'sss' p5 B 谁能告诉我如何

我的代码(我无法使用“pickle”):

打印:

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>
www
aaaa
ccopy_注册
_重建器
p0
(c___)主要__
A.
p1
c__内置__
对象
p2
Ntp3
Rp4
S'sss'
p5
B

谁能告诉我如何使用。

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


不必关心这些串字符串,您可以转储这些字符串以保存到任何位置,只要记住当您加载它们时,您又得到了一个“a”对象。

您可以
pickle
(意思是,此代码按它应该的方式工作)。您似乎得到了一个结果,但并不期望得到结果。如果您期望得到相同的“输出”,请尝试:

import pickle
a = A()
s = pickle.dumps(a)
e = pickle.loads(s)
print s, pickle.dumps(e)
您的示例不是一个典型的“pickle”示例。通常,pickle对象会永久保存在某个位置或通过网络发送。请参见例如
pickletest.py


酸洗有很多高级用途,例如,请参见David Mertz XML对象序列化文章:

您想做什么?它对我有用:

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
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