python多处理:AttributeError:无法pickle本地对象
我在一个类中有一个方法来返回一个func,它的参数可能会改变 接口函数接受两个参数,f及其参数。我想使用mp.pool来加速它。但是,它返回一个错误python多处理:AttributeError:无法pickle本地对象,python,Python,我在一个类中有一个方法来返回一个func,它的参数可能会改变 接口函数接受两个参数,f及其参数。我想使用mp.pool来加速它。但是,它返回一个错误 from multiprocessing import Pool # from multiprocess import Pool # from pathos.multiprocessing import ProcessingPool as Pool import pickle import dill class Temp: def __
from multiprocessing import Pool
# from multiprocess import Pool
# from pathos.multiprocessing import ProcessingPool as Pool
import pickle
import dill
class Temp:
def __init__(self, a):
self.a = a
def test(self):
def test1(x):
return self.a + x
return test1
def InterfaceFunc(f, x):
mypool = Pool(4)
return list(mypool.map(f, x))
if __name__ == "__main__":
t1 = Temp(1).test()
x = [1, 2, 3, 1, 2]
res1 = list(map(t1, x))
print(res1)
res2 = InterfaceFunc(t1, x)
它引发了同样的错误:
AttributeError: Can't pickle local object 'Temp.test.<locals>.test1'
它会引发错误:
File "E:\Users\ll\Anaconda3\lib\site-packages\dill\_dill.py", line 577, in _load_type
return _reverse_typemap[name]
KeyError: 'ClassType'
Method3需要更改代码,但是我不能简单地将func移出类,因为我需要f作为接口的参数
你有什么建议吗?我是一个没有经验的新手 Python无法对闭包进行pickle处理,但您真正需要的是可以调用的保留状态的东西。方法使类实例可调用,因此使用
from multiprocessing import Pool
class TempTest1:
def __init__(self, a):
self.a = a
def __call__(self, x):
return self.a + x
class Temp:
def __init__(self, a):
self.a = a
def test(self):
return TempTest1(self.a)
def InterfaceFunc(f, x):
mypool = Pool(4)
return list(mypool.map(f, x))
if __name__ == "__main__":
t1 = Temp(1).test()
x = [1, 2, 3, 1, 2]
res1 = list(map(t1, x))
print(res1)
res2 = InterfaceFunc(t1, x)
print(res2)
您的示例无法运行,这使得使用解决方案进行实验变得更加困难。@t抱歉,我以前犯了一个错误。我更改了代码,它引发了一个异常。我不知道链接的问题如何回答这个问题。在那里,OP可以将函数移到模块级,但这里不是这样,因为调用还有需要管理的状态。
from multiprocessing import Pool
class TempTest1:
def __init__(self, a):
self.a = a
def __call__(self, x):
return self.a + x
class Temp:
def __init__(self, a):
self.a = a
def test(self):
return TempTest1(self.a)
def InterfaceFunc(f, x):
mypool = Pool(4)
return list(mypool.map(f, x))
if __name__ == "__main__":
t1 = Temp(1).test()
x = [1, 2, 3, 1, 2]
res1 = list(map(t1, x))
print(res1)
res2 = InterfaceFunc(t1, x)
print(res2)