前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 函数回调

python 函数回调

作者头像
用户5760343
发布2019-10-21 11:45:48
8480
发布2019-10-21 11:45:48
举报
文章被收录于专栏:sktj

回调函数

def apply_async(func, args, , callback): # Compute the result result = func(args)

代码语言:javascript
复制
# Invoke the callback with the result
callback(result)

调用

def print_result(result): ... print('Got:', result) ... def add(x, y): ... return x + y ... apply_async(add, (2, 3), callback=print_result) Got: 5 apply_async(add, ('hello', 'world'), callback=print_result) Got: helloworld

协程处理回调

还有另外一个更高级的方法,可以使用协程来完成同样的事情:

def make_handler(): sequence = 0 while True: result = yield sequence += 1 print('[{}] Got: {}'.format(sequence, result)) 对于协程,你需要使用它的 send() 方法作为回调函数,如下所示:

handler = make_handler() next(handler) # Advance to the yield apply_async(add, (2, 3), callback=handler.send) [1] Got: 5 apply_async(add, ('hello', 'world'), callback=handler.send) [2] Got: helloworld

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.10.18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 回调函数
  • 调用
  • 协程处理回调
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档