多重处理:AttributeError:“导入的”对象没有属性“ __private_method”

时间:2018-08-14 12:56:13

标签: python python-3.x multiprocessing pickle

我在工作代码中遇到了这个问题,因此无法显示。但是我写了一个简短的示例,该示例准确地再现了错误并切断了冗余逻辑。

示例包含两个文件:Example.pyImportedExample.py

Example.py

from multiprocessing import Process
from ImportedExample import Imported

class Example:
    def __init__(self, number):
        self.imported = Imported(number)

def func(example: Example):
    print(example)

if __name__ == "__main__":
    ex = Example(3)

    p = Process(target=func, args=(ex,))
    p.start()

ImportedExample.py

class Imported:
    def __init__(self, number):
        self.number = number
        self.ref = self.__private_method

    def __private_method(self):
        print(self.number)

Traceback看起来像这样:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File"C:\Python\Python36\lib\multiprocessing\spawn.py", line 105, in spawn_main 
exitcode = _main(fd)
  File "C:\Python\Python36\lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
AttributeError: 'Imported' object has no attribute '__private_method'

主要细节是,当我将__private_method()设为非私有(重命名为private_method())时,一切正常。

我不明白为什么会这样。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

multiprocessing模块使用pickle在进程之间传输对象。

要使对象可拾取,必须按名称对其进行访问。多亏private name mangling,引用的私有方法才不在该类别之内。

我建议将方法设为受保护的 –即仅用一个下划线命名该方法。从全局的角度来看,应该将受保护的方法视为私有方法,但是它们不是名称修改的主题。