带有额外状态的回调函数
编码中常碰到的一个情形是需要编写回调函数,如事件处理函数等。一般的回调函数如常规函数,传递参数,返回计算的值。 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 >>> 注意到,print_result()函数仅接受一个参数,即result。 没有其他信息传递。当希望回调函数与环境的其他变量或部分交互时,信息的缺乏有时会带来问题。 在回调中携带额外状态或信息的一种方式是使用绑定的方法而不是一个简单的函数。比如说使用类定义。如下所示: class ResultHandler: def __init__(self): self