python中利用Future對象回調別的函數範例程式碼,pythonfuture
前言
本文主要給大家介紹了關於python中用Future對象回調別的函數的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
Future對象也可以像協程一樣,當它設定完成結果時,就可以立即進行回調別的函數
例子如下:
import asyncio import functools def callback(future, n): print('{}: future done: {}'.format(n, future.result())) async def register_callbacks(all_done): print('registering callbacks on future') all_done.add_done_callback(functools.partial(callback, n=1)) all_done.add_done_callback(functools.partial(callback, n=2)) async def main(all_done): await register_callbacks(all_done) print('setting result of future') all_done.set_result('the result') event_loop = asyncio.get_event_loop() try: all_done = asyncio.Future() event_loop.run_until_complete(main(all_done)) finally: event_loop.close()
輸出結果如下:
registering callbacks on futuresetting result of future1: future done: the result2: future done: the result
在這個例子裡,先調用函數add_done_callback()來註冊一個回呼函數,由於只支援一個參數,使用functools.partial來作一個封裝。當set_result()函數調用之後,就立即進行回呼函數的運行。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流,謝謝大家對幫客之家的支援。