一、什么是钩子函数
hook函数就是在一定条件下才会执行的函数,将自己实现的函数挂载到挂载点上
1. hook函数:就是我们自己实现的函数,函数类型与挂载点匹配(返回值,参数列表)2. 挂接:也就是hook或者叫注册(register),使得hook函数对目标可用
3. 目标挂载点:也就是挂我们hook函数的地方(我们想在这个目标点实现我们自己的功能
二、使用场景
一般在流程性的代码中会使用hook函数,挂载点可能会执行我们实现的函数,也可能不执行,当满足一定条件才会执行的情况下
import time class LazyPerson(object): def __init__(self, name): self.name = name self.watch_tv_func = None # 目标挂载点 self.have_dinner_func = None def get_up(self): print("%s get up at:%s" % (self.name, time.time())) def go_to_sleep(self): print("%s go to sleep at:%s" % (self.name, time.time())) def register_tv_hook(self, watch_tv_func): # 挂接 self.watch_tv_func = watch_tv_func def register_dinner_hook(self, have_dinner_func): self.have_dinner_func = have_dinner_func def enjoy_a_lazy_day(self): self.get_up() time.sleep(2) # watch tv --> check the watch_tv_func(hooked or unhooked) --> hooked if self.watch_tv_func is not None: self.watch_tv_func(self.name) else: # unhooked print("no tv to watch") time.sleep(2) # have dinner --> check the have_dinner_func(hooked or unhooked) --> hooked if self.have_dinner_func is not None: self.have_dinner_func(self.name) else: # unhooked print("nothing to eat at dinner") time.sleep(2) self.go_to_sleep() def watch_daydayup(name): # hook函数 print("%s : The program ---day day up--- is funny!!!" % name) def watch_happyfamily(name): print("%s : The program ---happy family--- is boring!!!" % name) def eat_meat(name): print("%s : The meat is nice!!!" % name) def eat_hamburger(name): print("%s : The hamburger is not so bad!!!" % name) def test(): lazy_tom = LazyPerson("Tom") lazy_jerry = LazyPerson("Jerry") # register hook lazy_tom.register_tv_hook(watch_daydayup) lazy_tom.register_dinner_hook(eat_meat) lazy_jerry.register_tv_hook(watch_happyfamily) lazy_jerry.register_dinner_hook(eat_hamburger) # enjoy a day lazy_tom.enjoy_a_lazy_day() lazy_jerry.enjoy_a_lazy_day() test()
钩子函数的实现就是通过一定的关系,将两个函数产生关联,例如上面的例子,register_tv_hook函数和watch_day_day_up通过self.watch_tv_func产生关联,如果要执行watch_tv_func函数,需要先进行注册(register_tv_hook),然后判断注册时传入的self.watch_tv_func是否为空,如果为空则表示注册未成功,则不执行我们自己写的函数watch_tv_func,如果不为空,则表示注册成功,则执行函数watch_day_day_up,大大扩展了类的可执行方法
参考文档:https://www.cnblogs.com/zhang-ye/p/16289417.html 、https://blog.csdn.net/RayMand168/article/details/128560646
标签:函数,hook,python,钩子,self,watch,tv,func,name From: https://www.cnblogs.com/renjie1105/p/17084962.html