gpt4 book ai didi

pickle - 不能pickle instancemethod 对象

转载 作者:行者123 更新时间:2023-12-03 10:08:20 25 4
gpt4 key购买 nike

我遇到了pickle的问题,代码是:

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)

错误是:

File "/usr/lib/python2.7/copy_reg.py", line 70, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.name TypeError: can't pickle instancemethod objects

最佳答案

如果您使用 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()

关于pickle - 不能pickle instancemethod 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34399656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com