在另一个方法中调用 ThreadPoolExecutor 时访问 class 的方法

Access methods of class when calling ThreadPoolExecutor in another method

我有一个异步检索一些数据的方法,必须调用其他方法来存储该数据。我正在使用 ThreadPoolExecutor 来获取该数据。

class是这样的:

class A:
    [...]
    def update_balance(self, exchange_name, balance):
        if balance is not None:
            self.exchanges[exchange_name].balance = balance

    def __balance_getter(ex, this):
            balance = ex.get_balance()
            if balance is not None:
                update_balance(ex.api.name, balance) ---> Can't call update_balance. I have no ref of self

    def retrieve_all_balances(self, exchange_list):
        with concurrent.futures.ThreadPoolExecutor() as executor:
            executor.map(self.__balance_getter, exchange_list)

如何将 self 的引用传递给 __balance_getter() 以便我可以调用 self.update_balance()

谢谢

重写 __balance_getter 使其只是 returns 信息。重写 retrieve_all_balances 以创建未来列表,然后在每个未来完成时将结果发送到 update_balance

class A:
    [...]
    def update_balance(self, exchange_name, balance):
        if balance is not None:
            self.exchanges[exchange_name].balance = balance

    def __balance_getter(ex, this):
            balance = ex.get_balance()
            return (ex.api.name, balance)
#            if balance is not None:
#                update_balance(ex.api.name, balance) ---> Can't call update_balance. I have no ref of self

    def retrieve_all_balances(self, exchange_list):
        with concurrent.futures.ThreadPoolExecutor() as executor:
            futures = [executor.submit(self.__balance_getter, arg) for arg in exchange_list]
            for future in concurrent.futures.as_completed(futures):
                name,balance = future.result()
                self.update_balance(name,balance)

无法真正测试这是否能解决您的问题,因为您没有提供 mcve