Python Future对象实现函数回调的示例解析

程一诺
程一诺
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍Python中利用Future对象实现函数回调的方法。通过add_done_callback注册回调,结合functools.partial处理多参数,在set_result设置结果时触发回调执行。示例展示了如何在异步编程中注册并触发回调函数,适用于需要结果通知的场景。

前言

本文主要介绍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 future
setting result of future
1: future done: the result
2: future done: the result

在该示例中,首先调用函数add_done_callback()来注册一个回调函数。由于该回调仅支持单个参数,因此使用functools.partial进行封装处理。当set_result()函数被调用后,回调函数将立即执行。

总结

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助。如果有疑问,欢迎留言交流,感谢大家对本站的支持。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表