菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
2312
0

回调函数

原创
05/13 14:22
阅读数 2143

回调函数

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, ('hello', 'world'), callback=print_result) 
>>> Got: helloworld

实用类封装实现

class ResultHandler: def __init__(self):
        self.sequence = 0
def handler(self, result):
self.sequence += 1
print('[{}] Got: {}'.format(self.sequence, result))

使用这个类的时候,你先创建一个类的实例,然后用它的 handler() 绑定方法来 做为回调函数:

>>> r = ResultHandler()
>>> apply_async(add, (2, 3), callback=r.handler)
[1] Got: 5
>>> apply_async(add, ('hello', 'world'), callback=r.handler) [2] Got: helloworld
>>>

第二种方式,作为类的替代,可以使用一个闭包捕获状态值

def make_handler():
    sequence = 0
    def handler(result):
        nonlocal sequence
        sequence += 1
        print('[{}] Got: {}'.format(sequence, result))

闭包例子

>>> handler = make_handler()
>>> apply_async(add, (2, 3), callback=handler)
[1] Got: 5
>>> apply_async(add, ('hello', 'world'), callback=handler) [2] 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
>>>

发表评论

0/200
2312 点赞
0 评论
收藏
为你推荐 换一批