不能腌制instancemethod对象

时间:2015-12-21 15:58:06

标签: pickle instance-methods

我遇到了泡菜问题,代码就是:

import cPickle

class A(object):

    def __init__(self):
        self.a = 1

    def methoda(self):
        print(self.a)


class B(object):

    def __init__(self):
        self.b = 2
        a = A()
        self.b_a = a.methoda

    def methodb(self):
        print(self.b)
if __name__ == '__main__':
    b = B()
    with open('best_model1.pkl', 'w') as f:
        cPickle.dump(b, f)

错误是:

  

文件" /usr/lib/python2.7/copy_reg.py",第70行,在_reduce_ex中       引发TypeError,"不能腌制%s对象" %base。名称 TypeError:无法腌制instancemethod对象

2 个答案:

答案 0 :(得分:3)

如果您使用dill代替cPickle,则可以。

>>> import dill     
>>> 
>>> class A(object):
...   def __init__(self):
...     self.a = 1
...   def methods(self):
...     print(self.a)
... 
>>> 
>>> class B(object):
...   def __init__(self):
...     self.b = 2
...     a = A()
...     self.b_a = a.methods
...   def methodb(self):
...     print(self.b)
... 
>>> b = B()
>>> b_ = dill.dumps(b)
>>> _b = dill.loads(b_)
>>> _b.methodb()
2
>>> 

另见: Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool.map()

答案 1 :(得分:0)

此外,当安装莳萝时,泡菜可以使用,但照常不能使用cPickle。

import cPickle, pickle

class A(object):
    def __init__(self):
        self.a = 1
    def methoda(self):
        print(self.a)

class B(object):
    def __init__(self):
        self.b = 2
        a = A()
        self.b_a = a.methoda
    def methodb(self):
        print(self.b)

# try using cPickle
try:
    c = cPickle.dumps(b)
    d = cPickle.loads(c)
except Exception as err:
    print('Unable to use cPickle (%s)'%err)
else:
    print('Using cPickle was successful')
    print(b)
    print(d)

# try using pickle
try:
    c = pickle.dumps(b)
    d = pickle.loads(c)
except Exception as err:
    print('Unable to use pickle (%s)'%err)
else:
    print('Using pickle was successful')
    print(b)
    print(d)

 >>> Unable to use cPickle (can't pickle instancemethod objects)
 >>> Using pickle was successful
 >>> <__main__.B object at 0x10e9b84d0>
 >>> <__main__.B object at 0x13df07190>

无论出于何种原因,cPickle都不只是酱菜的C版本快100倍,而是有一些差异