python 回调函数的使用_python 回调函数的简单使用

def apply_async(func, args=(), callable=None):

"""需要调用的回调函数的函数"""

result = func(*args) # 元组拆包*args

callable(result)

def print_result(result):

"""打印日志信息"""

print("Got:", result)

def add(x, y):

"""计算函数"""

return x + y

class ResultHandler:

"""第一种 保存内部序列号"""

def __init__(self):

self.sequence = 0

def handler(self, result):

self.sequence += 1

print('[{}] Got:{}'.format(self.sequence, result))

def make_handler():

"""第二种 类的替代,可以使用闭包捕获状态值"""

sequence = 0

def handler(result):

nonlocal sequence # 只能用于嵌套函数中

sequence += 1

print('[{}] Got:{}'.format(sequence, result))

return handler

def make_handler_2():

"""第三种 使用协程"""

sequence = 0

while True:

result = yield

sequence += 1

print('[{}] Got:{}'.format(sequence, result))

if __name__ == '__main__':

apply_async(add, (3, 4), callable=print_result)

apply_async(add, ("python", " callable"), callable=print_result)

r = ResultHandler()

apply_async(add, (2, 3), callable=r.handler)

apply_async(add, ('hello', ' world'), callable=r.handler)

handler = make_handler()

apply_async(add, (2, 3), callable=handler)

apply_async(add, ('hello', 'workd'), callable=handler)

print('='*50)

handler_2 = make_handler_2()

next(handler_2)

apply_async(add, (2, 3), callable=handler_2.send)

apply_async(add, ("hello", 'world'), callable=handler_2.send)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值