【问题标题】:Multiprocessing: AttributeError: 'Imported' object has no attribute '__private_method'多处理:AttributeError:“导入”对象没有属性“__private_method”
【发布时间】:2018-08-14 12:56:13
【问题描述】:

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

示例有两个文件: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()

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

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

【问题讨论】:

  • 酸洗似乎有些问题。
  • 感谢@pacholik 提供详细解答。他的解释为我清除了一切,他的建议解决了我的问题

标签: python python-3.x multiprocessing pickle


【解决方案1】:

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

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

我建议将方法设为protected——即只用一个前导下划线命名方法。从全局的角度来看,受保护的方法应该被视为私有方法,但它们不是名称修改的对象。

【讨论】:

    猜你喜欢
    • 2020-02-05
    • 2019-12-17
    • 2015-10-25
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多