抱歉,如果其他地方已经回答了这个问题。我环顾了互联网,却没有找到明确的答案

我有一个类定义(包含多个值和方法),并且列表中包含该类的多个实例。 (每个列表条目都是一个实例。)

当我尝试腌制列表时,出现“ 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'

最佳答案

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

docs

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

关于python - 获取异常pickle.dump,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14204647/

10-15 11:48