Pickle:AttributeError:'module'对象没有属性

Chi*_*kus 4 python pickle attributeerror

我发现了很多关于这个问题的线索,但所有这些问题都是命名空间.我的问题与命名空间无关.

一个小例子:

import cPickle as pickle
from uncertainties import Variable

class value(Variable):
    def __init__(self, args, showing=False):
        self.show = showing
        Variable.__init__(self, args[0], args[1])

val = value((3,1), True)
print val.nominal_value, val.std_dev(), val.show
fobj = file("pickle.file", "w")
pickle.dump(val, fobj)
fobj.close()

fobj = file("pickle.file", "r")
val = pickle.load(fobj)
fobj.close()
print val.nominal_value, val.std_dev(), val.show
Run Code Online (Sandbox Code Playgroud)

这段代码的输出:

3.0 1.0 True
3.0 1.0
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/usr/lib/python2.7/dist-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
    173             else:
    174                 filename = fname
--> 175             __builtin__.execfile(filename, *where)

/home/markus/pickle.py in <module>()
     19 val = pickle.load(fobj)
     20 fobj.close()
---> 21 print val.nominal_value, val.std_dev(), val.show

AttributeError: 'value' object has no attribute 'show'
Run Code Online (Sandbox Code Playgroud)

酸洗和去斑纹时的命名空间是相同的.uncertainties.Variable恢复所有属性- 仅错过我添加的一个"节目".

Mar*_*ers 6

uncertainties.Variable()采用的是__slots__属性以节省内存.因此,要成为pickleable,它还必须定义一个__getstate__方法(请参阅为什么我在尝试pickle一个对象时得到关于定义__slots__的类的错误?).

如果您需要添加自己的附加属性,则必须覆盖该__getstate__方法.在__slot__您自己的属性中声明其他属性也可能是一个好主意:

from uncertainties import Variable

class value(Variable):
    __slots__ = ('show',)  # only list *additional* slots

    def __init__(self, args, showing=False):
        self.show = showing
        super(value, self).__init__(args[0], args[1])

    def __getstate__(self):
        obj_slot_values = {}
        for cls in type(self).mro():
            obj_slot_values.update((k, getattr(self, k)) for k in getattr(cls, '__slots__', ()))
        # Conversion to a usual dictionary:
        return obj_slot_values
Run Code Online (Sandbox Code Playgroud)

这个新的__getstate__是必需的,因为该Variable.__getstate__方法假设只有一个 __slots__属性,而MRO中的每个类可能有一个属性.

这实际上是uncertainties图书馆的限制; 我已经提交了一个解决此问题的pull请求,并且不再需要覆盖__getstate__子类中的方法.