Home > database >  How to pass arguments to class after initialized?
How to pass arguments to class after initialized?

Time:10-29

I'm trying to create threads to run a class method. However, when I try to pass one class to another, it tries to initialize the class and never gets threaded.

I'm taking a list of tuples and trying to pass that list to the cfThread class, along with the class method that I want to use. From here, I'd like to create a separate thread to run the classes method and take action on one of tuples from the list. The REPLACEME is a placeholder because the class is looking for a tuple but I don't have one to pass to it yet. My end goal is to be able to pass a target (class / function) to a thread class that can create it's own queue and manage the threads without having to manually do it.

Below is a simple example to hopefully do a better job of explaining what I'm trying to do.

#!/bin/python3.10
import concurrent.futures

class math:
    def __init__(self, num) -> None:
        self.num = num

    def add(self):
        return self.num[0]   self.num[1]

    def sub(self):
        return self.num[0] - self.num[1]

    def mult(self):
        return self.num[0] * self.num[1]

class cfThread:
    def __init__(self, target, args):
        self.target = target
        self.args = args

    def run(self):
        results = []
        with concurrent.futures.ThreadPoolExecutor(10) as execute:
            threads = []
            for num in self.args:
                result = execute.submit(self.target, num)
                threads.append(result)
            for result in concurrent.futures.as_completed(threads):
                results.append(result)
        return results


if __name__ == '__main__':
    numbers = [(1,2),(3,4),(5,6)]
    results = cfThread(target=math(REPLACEME).add(), args=numbers).run()
    print(results)

CodePudding user response:

target has to be a callable; you want to wrap your call to add in a lambda expression.

results = cfThread(target=lambda x: math(x).add(), args=numbers)
  • Related