-1

我想坚持从reverend.thomas.Bayes. 当然,如果我尝试直接腌制这些类之一,我会得到:

TypeError: can't pickle instancemethod objects

为了解决这个问题,我尝试声明两个函数:

import types
from itertools import chain
from copy import copy
from reverend.thomas import Bayes

def prepare_bayes_for_pickle(bayes_obj):
    dic = copy(bayes_obj.__dict__) #I also tried using deepcopy instead of copy
    for k in dic:
        if type(k) == types.MethodType:
            dic.pop(k)
    return dic

def reconstruct_bayes_from_pickle(bayes_dic):
    b = Bayes()
    # Merge b with bayes_dic, with bayes_dic taking precedence
    dic = dict(chain(bayes_dic, b))
    b.__dict__ = dic
    return b

基本上,我尝试复制对象的__dict__,并尝试instancemethod通过测试类型来删除 s types.MethodType

然后,我将通过创建一个新Bayes对象然后将其重新合并来重建该对象bayes_dic(在它被 UnPickled 之后。)

但是,我还没有使用第二种方法,因为我仍然无法在prepare_bayes_for_pickle没有得到原始错误的情况下腌制从返回的对象。

4

3 回答 3

2

更好的解决方案是让您__getstate__在类中添加一个方法Bayes(附带__setstate__):

import types
from reverend.thomas import Bayes

def Bayes__getstate__(self):
    state = {}
    for attr, value in self.__dict__.iteritems():
        if not isinstance(value, types.MethodType):
            state[attr] = value
        elif attr == 'combiner' and value.__name__ == 'robinson':
            # by default, self.combiner is set to self.robinson
            state['combiner'] = None
    return state

def Bayes__setstate__(self, state):
    self.__dict__.update(state)
    # support the default combiner (an instance method):
    if 'combiner' in state and state['combiner'] is None:
        self.combiner = self.robinson

Bayes.__getstate__ = Bayes__getstate__
Bayes.__setstate__ = Bayes__setstate__

现在Bayes类总是可以被腌制和解除腌制,而无需额外的处理。

我确实看到这个类有一个self.cache = {}映射;也许酸洗时应该排除?如果是这种情况,请忽略它__getstate__并打电话self.buildCache()__setstate__

于 2013-03-19T12:21:54.007 回答
0

k is a key i.e. the attribute/method name. You need to test the attribute itself:

    if type(dic[k]) == types.MethodType:
            ^~~~~~ here

I'd prefer using a comprehension; you should also be using isinstance:

dic = dict((k, v) for k, v in bayes_obj.__dict__
           if not isinstance(v, types.MethodType))
于 2013-03-19T12:16:46.940 回答
0

这听起来像是让一个方形钉子适合一个圆孔。如何使用 pickle 来腌制参数,并使用 unpickle 来重建reverand.Thomas.Bayes对象?

>>> from collections import namedtuple
>>> ArgList = namedtuple('your', 'arguments', 'for', 'the', 'reverand')
>>> def pickle_rtb(n):
...     return pickle.dumps(ArgList(*n.args))
... 
>>> def unpickle_rtb(s):
...     return reverand.Thomas.Bayes(*pickle.loads(s))
... 
>>> s = pickle_rtb(reverand.Thomas.Bayes(1, 2, 3, 4, 5)) # note arguments are a guess
>>> rtb = unpickle_norm(s)

这个SO question 的启发。

于 2013-03-19T12:21:30.067 回答