python - pickle : using both __getstate__ and __getnewargs__

标签 python python-2.7 pickle

我在 python 2.7 上使用 pickle。我正在尝试调用我覆盖的两种方法 __getstate____getnewargs__ 。我不能 pickle 属性 c 因为它是类 D 的一个实例。

 nn = C(7, 2)
 nn.d = 1
 pickle.dump(nn, open('c_save.p', 'wb'))
 nn2 = pickle.load(open('c_save.p', 'rb'))
 print nn2.__dict__

返回:

getstate was called
setstate was called
{'a': 7, 'b': 2, 'd': 1}

我没有看到应该创建属性 c__getnewargs__ 调用。

我的代码:

import pickle

class D(object):
    def __init__(self, i, j):
        self.i = i
        self.j = j

class C(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.c = D(a, b)
        self.d = 0

    def __getstate__(self):
        print 'getstate was called'
        odict = self.__dict__.copy()
        del odict['c']
        return odict

    def __getnewargs__(self):
        print 'getnewargs was called'
        return (self.b,self.a)

    def __setstate__(self, dict):
        print 'setstate was called'
        self.__dict__.update(dict)

最佳答案

来自docs :

New-style types can provide a getnewargs() method that is used for protocol 2.

对于 pickle.dump :

If the protocol parameter is omitted, protocol 0 is used.

因此,您必须像这样显式地将 pickle 协议(protocol)设置为 2:

pickle.dump(nn, open('c_save.p', 'wb'), protocol=2)

关于python - pickle : using both __getstate__ and __getnewargs__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43538628/

相关文章:

Python 2.7 和 MySQL : grooming tuple

python - 在 python 27 中,如何将带参数的方法传递给类的 __init__()?

python - 将字符串转换为有序字典?

python - 如果pickle文件中不存在对象,则创建新对象,如果存在则加载它(多个对象的最佳方法?)

python - pyqt:如何让QLabel占据整个窗口

python - 除一个特定值外,如何将 numpy 数组中的所有值替换为零?

python - 过滤一个 Excel 工作表中的数据框并导出到另一个 Excel 工作表

python - Odoo 在模块更新后不添加新的 XML 文件

python - 攻击 Python 的 pickle

python - 无法在 Mac 上取消在 Windows 上 pickle 的文件