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)

posted on 2019-11-29 14:22  action555  阅读(638)  评论(0编辑  收藏  举报