我有一个方法可以异步检索某些数据,并且必须调用其他方法来存储该数据。我正在使用ThreadPoolExecutor
获取该数据。
该类是这样的:
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)
如何将__balance_getter()
的引用传递给self
,以便可以调用self.update_balance()
?
谢谢
重写__balance_getter
,以便它返回信息。重写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):
self.update_balance(*future.result())
无法真正测试这是否解决了您的问题,因为您没有提供mcve。