自定义类的泡菜 [英] Pickle with custom classes

查看:82
本文介绍了自定义类的泡菜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在myClass.py文件中有一个简单的python类定义

Suppose I have a simple python class definition in a file myClass.py

class Test:
    A = []

我也有两个测试脚本.第一个脚本创建类型为Test的对象,填充数组A,并将结果腌制到文件中.它立即将其从文件中删除,并且仍在填充阵列. 第二个脚本只是从文件中释放,并且不填充数组(即A == []).为什么会这样?

And I also have two test scripts. The first script creates an object of type Test, populates the array A, and pickles the result to a file. It immediately unpickles it from the file and the array is still populated. The second script just unpickles from the file, and the array is not populated (i.e. A == []). Why is this?

test1.py

import myClass
import pickle

x = myClass.Test()

for i in xrange(5):
    x.A.append(i)

f = open('data', 'w')
pickle.dump(x,f)
f.close()

f = open('data')
y = pickle.load(f)
f.close

print y.A

和test2.py

import myClass
import pickle

f = open('data')
y = pickle.load(f)
f.close

print y.A

推荐答案

这是因为您将Test.A设置为类属性而不是实例属性.真正发生的是使用test1.py,从pickle文件读取的对象与test2.py相同,但是它使用的是您最初分配x.A的内存中的类.

It is because you are setting Test.A as a class attribute instead of an instance attribute. Really what is happening is that with the test1.py, the object being read back from the pickle file is the same as test2.py, but its using the class in memory where you had originally assigned x.A.

从文件中解数据时,它将创建该类类型的新实例,然后将其需要的任何实例数据应用到该实例中.但是,您唯一的数据是类属性.它总是引用内存中的类thats,您在一个文件中修改了该类,而在另一个文件中没有修改.

When your data is being unpickled from the file, it creates a new instance of the class type, and then applies whatever instance data it needs to. But your only data was a class attribute. Its always referring back to the class thats in memory, which you modified in one, but not in another file.

比较此示例中的差异:

class Test:
    A = []  # a class attribute
    def __init__(self):
        self.a = []  # an instance attribute

您会注意到实例属性a将被正确地酸洗和去酸,而类属性A将仅引用内存中的类.

You will notice that the instance attribute a will be pickled and unpickled properly, while the class attribute A will simply refer to the class in memory.

for i in xrange(5):
    x.A.append(i)
    x.a.append(i)  

with open('data', 'w') as f:
    pickle.dump(x,f)

with open('data') as f:
    y = pickle.load(f)

>>> y.A
[0, 1, 2, 3, 4]
>>> y.a
[0, 1, 2, 3, 4]
>>> Test.A
[0, 1, 2, 3, 4]
>>> Test.A = []  # resetting the class attribute
>>> y.a 
[0, 1, 2, 3, 4]
>>> y.A  # refers to the class attribute
[]

这篇关于自定义类的泡菜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆