美文网首页Python
python 函数回调

python 函数回调

作者: SkTj | 来源:发表于2019-10-18 10:46 被阅读0次

回调函数

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

# 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

相关文章

  • python 函数回调

    回调函数 def apply_async(func, args, , callback):# Compute th...

  • 理解 Python 装饰器与回调函数

    1.理解 Python 装饰器2.Python装饰器和回调函数回调函数就是一个通过函数指针调用的函数。如果你把函数...

  • Kotlin多参数回调

    1、单个参数回调: 2、多个参数回调: 3、java中调用Kotlin的回调 1、java中调用Kotlin回调 ...

  • flutter 函数回调

    习惯使用java的同学一定经常使用java的接口回调,flutter本事不支持内部类,所以无法像java一样实现接...

  • Promise原理解析,使用ES5实现Promise

    Promise js的单线程特性导致大量的异步操作,异步操作我们通常使用函数回调的方式实现。大量的函数回调会产生我...

  • 第十九章 公私有变量及特权方法

    一,函数回调 回调函数 (优化性能 ) callback is function什么时候去使用回调函数呢? DO...

  • c函数回调oc

    1、c语言回调可以用self的静态传入调用方法,也可以用类设置delegate传出来,记得置nil 2、try c...

  • Activity跳转参数回调

    1.A-Activity首先携带数据跳转B-Activity 2.接收A-Activity的数据,把处理完的数据s...

  • React Native 函数回调

    子组件传递事件到父组件 碰到一个需求是:在子组件中点击按钮,需要将点击事件传递到父组件中,这个需求在iOS中可以很...

  • 封装函数回调结果

    场景:通常我们会封装请求函数,传入不同请求字段进行请求,这时候需要在不同业务场所请求返回不同回调结果,进而进行不同...

网友评论

    本文标题:python 函数回调

    本文链接:https://www.haomeiwen.com/subject/ywyfpctx.html