钩子hook,回调函数callback
摘自和参考如下资料:
把钩子函数传递给触发函数,就可以在触发函数内调用钩子函数了。其实就是把函数指针或者函数名传给另一个函数。只不过一般不单独这么用,配合类一起用可能就稍微麻烦了点。
class Oneday():
def __init__(self,name):
self.name_ = name
self.hook = None
def register_mouse_press_hook(self,hook_fn): # hook_fn是需要传入的钩子函数
self.hook = hook_fn
def on_left_key_down(self): # 触发函数,也可以看作是触发事件
print("Start from here:")
if self.hook is not None:
self.hook(self.name_)
else:
print("Not hooked, there is nothing to monitoring!")
print("Done!")
# 钩子函数的具体内容
def fn(name):
print("Hello, %s"%name)
today = Oneday('mxj')
today.register_mouse_press_hook(fn) # 这里是正式的将钩子函数作为实参传入
today.on_left_key_down() # 触发
# 输出:
# Start from here:
# Hello, mxj
# Done!

浙公网安备 33010602011771号