我最近看到了一个关于函数如何在 python 中成为对象的答案/评论。所以,我想知道为什么当我举这个例子,并在初始化变量时围绕它创建一个类时,它的工作方式不同。(类示例收到酸洗错误):
PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
有人知道为什么吗?
链接中的示例代码:
import multiprocessing as mp
def f(x):
f.q.put('Doing: ' + str(x))
return x*x
def f_init(q):
f.q = q
def main():
jobs = range(1,6)
q = mp.Queue()
p = mp.Pool(None, f_init, [q])
results = p.imap(f, jobs)
p.close()
for i in range(len(jobs)):
print q.get()
print results.next()
if __name__ == '__main__':
main()
f
放入类时的相同示例:
import multiprocessing as mp
class F:
def __init__(self, q):
self.q = q
def f(x):
self.q.put('Doing: ' + str(x))
return x*x
def main():
jobs = range(1,6)
q = mp.Queue()
p = mp.Pool(None)
f = F(q)
results = p.imap(f.f, jobs)
p.close()
for i in range(len(jobs)):
print q.get()
print results.next()
if __name__ == '__main__':
main()