2

如果这已经在其他地方得到回答,我们深表歉意。我浏览了互联网并没有找到明确的答案

我有一个类定义(包含几个值和方法),以及一个列表中保存的类的多个实例。(每个列表条目都是一个实例化。)

当我尝试腌制列表时,我得到一个“pickle.PicklingError”异常。这使我了解到有些对象不是“可腌制的”,但我的简单列表似乎应该没问题。

哪些对象是不可腌制的?

这是进行酸洗的实际代码。(此代码是在一个类内部定义的方法,它还包含我需要腌制的类对象。这是问题的一部分吗?)

def Write_Transaction_History_To_File(self):
    if (self.Transaction_History == True): # if History is not empty

        filename = self.Transaction_Name + '_Transaction_History.bin'
        f = open(filename, 'w')

        try:
            pickle.dump(self.Transaction_History , f, -1)   #use highest protocol
        except pickle.PicklingError:
            print 'Error when serializing data'
        f.close()

    else:
        print 'No History to store'
4

1 回答 1

3

如果您尝试腌制不在模块范围内的嵌套类,您将遇到麻烦。

文档

The following types can be pickled:


None, True, and False
integers, long integers, floating point numbers, complex numbers
normal and Unicode strings
tuples, lists, sets, and dictionaries containing only picklable objects
functions defined at the top level of a module
built-in functions defined at the top level of a module
classes that are defined at the top level of a module
instances of such classes whose __dict__ or the result of calling __getstate__() is 
picklable (see section The pickle protocol for details).
于 2013-01-07T21:54:04.853 回答