Pickled class 仅在应用程序处于 运行 时包含数据

Pickled class contains data only while application is running

我有一个脚本可以做一些事情,将结果保存到 class 变量然后 pickle 这个变量。 我还有另一个函数可以加载这个 pickle 文件并读取它。

如果我打开这个脚本,运行 首先运行(pickle 到文件)然后运行 ​​unpickling 然后它 运行 没问题,我可以读取所有数据

如果我打开此脚本,运行 第一个功能(pickle 到文件),关闭应用程序,再次打开它并加载之前 pickle 的同一文件 class 仅包含默认值

代码示例:

class test_class:
    table = ["a","b","c"]

def f1():
    test_variable = test_class()
    test_variable.table.append("d")

    file = open(file, "wb")
    pickle.dump(test_variable, file, -1)
    file.close()

def f2():
    file = open(file, "rb")
    new_test_variable = pickle.load(file)
    print new_test_variable.table
    file.close()

工作:

f1()
f2()

那个输出:

a,b,c,d

不工作:

f1()
[closing program, reopening program]
f2()

不工作的输出:

a,b,c

怎么了?

此致

如果我没记错的话你应该看看 dill 模块: https://pypi.python.org/pypi/dill/0.1a1

您需要安装 dill 模块并将 import pickle 更改为 import dill as pickle,然后一切正常。这是因为 dill 扩展了 pythons pickle。

Dill is capable of pickling the following standard types:

  • none, type, bool, int, long, float, complex, str, unicode,
  • tuple, list, dict, file, buffer, builtin,
  • both old and new style classes,
  • instances of old and new style classes,
  • set, frozenset, array, lambda,
  • standard functions, functions with yields, nested functions
  • wrapperdescriptor, xrange, slice,

其他:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.

还有:

Try not to name variables as:

  • str
  • int
  • file
  • and so on

所以你应该改变

def f2():
    file = open(file, "rb")
    new_test_variable = pickle.load(file)
    print new_test_variable.table
    file.close()

收件人:

def f2():
    with open('filelocation', "rb") as pickleFile:
        new_test_variable = pickle.load(pickleFile)
        print new_test_variable.table

您通过在 classes 顶层定义 table 来创建 class 属性。只有实例属性会被腌制。

所以定义属性:

class TestClass(object):

    def __init__(self):
        self.table = ["a", "b", "c"]