Multiprocessing: AttributeError: 'Imported' object has no attribute '__private_method'

Multiprocessing: AttributeError: 'Imported' object has no attribute '__private_method'

我在工作代码中遇到了这个问题,所以我无法展示它。但是我写了一些简短的例子,它准确地重现了错误并切断了冗余逻辑。

示例有两个文件:Example.py & ImportedExample.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()

进口Example.py

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

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

追溯看起来像这样:

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())时,一切正常。

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

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

要使对象可拾取,它必须可以通过名称访问。感谢 private name mangling,引用的私有方法不属于该类别。

我建议将方法设置为 protected – 即仅使用一个前导下划线命名该方法。从全局的角度来看,受保护的方法应该被视为私有方法,但它们不受名称重整的影响。