[在Python中使用期货时如何获取列表对象以附加值?

问题描述 投票:1回答:1
from concurrent import futures

class MyClass:
    def __init__(self):
        self.mylist = []

    def test(self, i):
        self.mylist.append(i)

myclass = MyClass()

print(myclass.mylist)

ilist = [1, 2, 3, 4]

for i in ilist:
    myclass.test(i)

print(myclass.mylist)

myclass.mylist = []
with futures.ProcessPoolExecutor() as pool:
    for null in pool.map(myclass.test, ilist):
        pass

print(myclass.mylist)

输出:

[]
[1, 2, 3, 4]
[]

为什么在常规循环中将def test中的值附加到self.mylist而不在使用期货时有效?使用期货时如何允许追加功能?

python concurrent.futures
1个回答
0
投票

稍微调整一下程序,以便池执行的功能返回列表,还可以打印MyClass对象的地址。

from concurrent import futures

class MyClass:
    def __init__(self):
        self.mylist = []

    def test(self, i):
        print(hex(id(self)), self.mylist, i)
        self.mylist.append(i)
        return self.mylist

if __name__ == "__main__":
    myclass = MyClass()
    ilist = [1, 2, 3, 4]
    myclass.mylist = []
    with futures.ProcessPoolExecutor() as pool:
        for null in pool.map(myclass.test, ilist):
            print(f'Output of process: {null}')    
    print(f'addr: {hex(id(myclass))} , {myclass.mylist}')

提供输出

Output of process: [1]
Output of process: [2]
Output of process: [3]
Output of process: [4]
0x1b88e358860 [] 1
0x20bffa28908 [] 3
0x259844b87f0 [] 2
0x1d7546d8898 [] 4
addr: 0x20e5ebc5400 , []

您可以看到每个进程都在处理MyClass对象的不同副本。

© www.soinside.com 2019 - 2024. All rights reserved.