钩子hook,回调函数callback

摘自和参考如下资料:

 

把钩子函数传递给触发函数,就可以在触发函数内调用钩子函数了。其实就是把函数指针或者函数名传给另一个函数。只不过一般不单独这么用,配合类一起用可能就稍微麻烦了点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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!

 

posted @   Picassooo  阅读(86)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2021-02-01 转:matplotlib画图,plt.xx和ax.xx之间有什么差异
点击右上角即可分享
微信分享提示