首页 > 解决方案 > 如何在类本身中使用类函数运行 Python 的 ProcessPoolExecutor?

问题描述

希望我的标题有意义,如果不是,这是我正在谈论的一个例子

from concurrent.futures import ProcessPoolExecutor


class App:
    def __init__(self):
        pass

    def __funct(self, a, b):
        return a * b

    def doing_func_in_parallel(self, list_a, list_b):
        process_executors = ProcessPoolExecutor()
        process_futures = []
        for a, b in zip(list_a, list_b):
            process_future = process_executors.submit(self.__funct, a=a, b=b)

            process_futures.append(process_future)

        list_result = []
        for future in process_futures:
            list_result.append(future.result())
        return list_result


if __name__ == '__main__':
    test_app = App()
    list_a = [1, 2, 3]
    list_b = [1, 2, 3]
    print(test_app.doing_func_in_parallel(list_a, list_b))

当我尝试运行它时,我得到:

AttributeError: 'App' object has no attribute '__funct'

我不能调用 ProcessPoolExecutor 在同一个类中运行方法吗?有什么解决办法吗?

标签: pythonclassconcurrent.futures

解决方案


此错误与 Python 的命名约定有关。

双下划线将破坏类的属性名称,以避免类之间的属性名称冲突。Python 会自动在属性名称前面添加“_ClassName”,该属性名称前面有一个双下划线。阅读更多

要修复您的应用程序,只需将您的方法重命名为_funct.


推荐阅读