运行 Python 的 ProcessPoolExecutor 如何在 [=11th=] 本身中使用 class 函数?
How to run Python's ProcessPoolExexcutor with a class function within the class itself?
希望我的标题有意义,如果不是的话,这就是我所说的例子
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'
我可以不在同一个 class 中调用 ProcessPoolExecutor 运行 方法吗?有什么解决办法吗?
此错误与 Python 的命名约定有关。
Double underscore will mangle the attribute names of a class to avoid conflicts of attribute names between classes. Python will automatically add "_ClassName" to the front of the attribute name which has a double underscore in front of it. Read more
要修复您的应用程序,只需将您的方法重命名为 _funct
。
希望我的标题有意义,如果不是的话,这就是我所说的例子
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'
我可以不在同一个 class 中调用 ProcessPoolExecutor 运行 方法吗?有什么解决办法吗?
此错误与 Python 的命名约定有关。
Double underscore will mangle the attribute names of a class to avoid conflicts of attribute names between classes. Python will automatically add "_ClassName" to the front of the attribute name which has a double underscore in front of it. Read more
要修复您的应用程序,只需将您的方法重命名为 _funct
。