Files
Python_CookBook_repo/7.函数/10.在回调函数中携带额外的状态.py

44 lines
1.2 KiB
Python
Raw Permalink Normal View History

2025-09-10 16:12:45 +08:00
def apply_async(func, args, *, callback):
result = func(*args)
callback(result)
def print_result(result):
print(result)
def add(x, y):
return x + y
# 如果只是简单的调用回调函数,那直接用就可以了
apply_async(add, (1, 2), callback=print_result)
apply_async(add, ('hello', 'world'), callback=print_result)
# 但是,如果我想要知道这个函数被调用了几次,携带这些保存的信息返回,可以这样改写:
def make_handler():
sequence = 0
def handler(result):
nonlocal sequence
sequence += 1
print('[{}] Got: {}'.format(sequence, result))
return handler
handler = make_handler()
apply_async(add, (1, 2), callback=handler)
apply_async(add, (1, 2), callback=handler)
# 当然我们也能用协程去搞定它:
# 协程的复习在10.1中,单步调试你就看懂了
def make_handler_v2():
sequence = 0
while True:
result = yield
sequence += 1
print('[{}] Got: {}'.format(sequence, result))
handler = make_handler_v2()
next(handler)
apply_async(add, (1, 2), callback=handler.send)
apply_async(add, (1, 2), callback=handler.send)
apply_async(add, (1, 2), callback=handler.send)