一串实例的运行方法

2024-04-25 17:36:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图运行一个实例列表的方法,但不知道如何按顺序运行它们

我有一个相同对象的实例列表:

class myclass(object):
   def __init__(xxx):
      ...
   def method(a, b):
      do something using a and b, 
      a and b will not be modified, 
      also no return value.

对于列表mylist中的每个实例,我想执行mylist[i].method(a,b)

除了按顺序运行外,我可以更有效地执行此操作吗。 请注意ab不是全局的,但需要传递


Tags: and对象实例方法列表object顺序init
1条回答
网友
1楼 · 发布于 2024-04-25 17:36:39

根据您提供的详细信息,最简单的方法可能是创建一个允许使用ThreadPool.map的包装器函数

因为您提到了ab不会被修改,所以我将它们用作“全局范围”变量。如果它们不是,您需要找到另一种方法将它们传递给每个线程,也许可以使用.apply将任意参数传递给已执行的函数

from multiprocessing.pool import ThreadPool

a, b = 1, 2

class A:
    def method(self, a, b):
        print(a, b)

def wrapper(a_object):
    a_object.method(a, b)

objects = [A() for _ in range(5)]

pool = ThreadPool()  # with no arguments this will create N threads,
                     # N being the number of CPUs that Python detects.
pool.map(wrapper, objects)
#  1 2
#  1 2
#  1 2
#  1 2
#  1 2

相关问题 更多 >