我想坚持从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
没有得到原始错误的情况下腌制从返回的对象。