wdcsx 发表于 2015-12-1 14:21:05

怎么解决python中TypeError: can't pickle instancemethod objects的这个错误

  最近在用python的cPickle和Pickle模块来序列化,如果对序列化不了解,可以点击这里,序列化的时候遇到一个问题



TypeError: can't pickle instancemethod objects
  在谷歌百度上查了很多,但是终究没有答案,我突然想,一般如果类比较简单,不能是不被pickle的,所以我想,一定是初始化一个实例的时候实例的属性某些属性导致不能被pickle,那么如果判断哪些属性是不能被pickle的呢?这里可以通过写一个函数来实现


[*]首先在类中定义__getstate__()函数
[*]


def __getstate__(self):
return self.__dict__
[*]然后你可以定义get_pickling_errors()函数
[*]


1 import pickle
2 def get_pickling_errors(obj,seen=None):
3   if seen == None:
4         seen = []
5   try:
6         state = obj.__getstate__()
7   except AttributeError:
8         return
9   if state == None:
10         return
11   if isinstance(state,tuple):
12         if not isinstance(state,dict):
13             state=state
14         else:
15             state=state.update(state)
16   result = {}   
17   for i in state:
18         try:
19             pickle.dumps(state,protocol=2)
20         except pickle.PicklingError:
21             if not state in seen:
22               seen.append(state)
23               result=get_pickling_errors(state,seen)
24   return result
[*]那如何使用呢?
[*]


>>> my_instance = My_Class()
>>> get_pickling_errors(my_instance)
{'_gen': {}, '_base': {'_gens': None}}
  这说明类My_Class的实例my_instance的属性_gen以及其父类的_gen是不能被pickle的

  通过上面的方法,我找到了不能被pickle的实例的属性.成功解决了我的问题.
页: [1]
查看完整版本: 怎么解决python中TypeError: can't pickle instancemethod objects的这个错误