【问题标题】:Getting an Exception pickle.dump获取异常 pickle.dump
【发布时间】:2012-12-21 16:41:48
【问题描述】:

如果这已经在其他地方得到回答,我们深表歉意。上网查了也没找到明确的答案

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

当我尝试腌制列表时,我得到一个“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'

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

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

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

    【讨论】:

    • 嗯。这可能是问题所在。这里所有相关的东西都是一个类的属性,称之为A类。A类包含另一个类的定义,B类(只在这里使用过)。要腌制的对象是A类的一个属性,它是B类的实例化列表。做腌制的函数是A类中的方法。我不知道,这种情况是否构成“不在模块中的嵌套类”范围”?感谢您的帮助。
    • 如果类中包含了另一个类的定义,那么这是一个问题,是的。
    • 也阅读stackoverflow.com/questions/1947904/…,有一些骇人听闻的解决方法——最好的办法可能是重构你的类。
    • 这个问题几乎可以肯定是我的问题的原因。这会很痛苦,但我宁愿重构代码也不愿使用变通方法。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 2013-03-01
    • 2019-05-15
    • 2018-08-14
    • 2019-10-13
    • 2018-08-18
    • 2011-04-10
    相关资源
    最近更新 更多