python中利用Future對象回調別的函數範例程式碼,pythonfuture

來源:互聯網
上載者:User

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()函數調用之後,就立即進行回呼函數的運行。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流,謝謝大家對幫客之家的支援。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.