实际上,回调、注册以及钩子的意思是一样的,都是指一个函数调用了其他的函数,而产生了不同的效果。
回调函数案例
回调(callback)是指一段以参数的形式传递给其它代码的可执行代码。
回调函数是以参数的形式传递给其他函数的函数,接收回调函数的函数根据传入的回调函数不同,产生不同的功能。
def callback1():
return 'hello!'
def callback2():
return 'hi!'
def saysomething(sentence = None,callback = None):
print('\n')
head = callback()
print(head)
print(sentence)
if __name__ == '__main__':
sentence = 'long time no see'
saysomething(sentence,callback1)
print('**************'*5)
saysomething(sentence,callback2)
代码执行的效果:
hello!
long time no see
*******************************************
hi!
long time no see
上述代码中,saysomething函数根据传入的回调函数不同而决定是以hello开头的打招呼方式还是以hi开头的打招呼方式。
钩子函数案例
所谓钩子函数就是指我们自己实现了一个特定的函数,来挂接到某个挂载点上,以实现特定的功能。因此需要注意的是,我们自己实现的这个钩子函数需要与挂载点的函数有相同的参数列表和返回值。
import time
class LazyPerson:
def __init__(self, name):
self.name = name
self.watch_tv_func = None
self.have_dinner_func = None
def get_up(self):
print("{} get up at:{}".format(self.name,time.time()))
def go_to_sleep(self):
print('{} go to sleep at:{}'.format(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):
# get up
self.get_up()
time.sleep(3)
# 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)
# unhooked
else:
print('no tv to watch')
time.sleep(3)
# 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)
# unhooked
else:
print('nothing to eat')
time.sleep(3)
self.go_to_sleep()
def watch_daydayup(name):
print('{}:daydayup is very funny! ha ha ha...'.format(name))
def watch_dahuaxiyou(name):
print('{}:men are too diffcult'.format(name))
def eat_beef(name):
print('{}:oh, the meet is delicious'.format(name))
def eat_icecream(name):
print('{}:too sweet'.format(name))
if __name__ == '__main__':
lazy_tom = LazyPerson('Tom')
lazy_jerry = LazyPerson('Jerry')
# register hook
lazy_tom.register_tv_hook(watch_daydayup)
lazy_tom.register_dinner_hook(eat_beef)
lazy_jerry.register_tv_hook(watch_dahuaxiyou)
lazy_jerry.register_dinner_hook(eat_icecream)
# enjoy a day
lazy_tom.enjoy_a_lazy_day()
lazy_jerry.enjoy_a_lazy_day()
如上述代码所示,我们定义的这个懒人类有四种行为(起床,睡觉,看电视,吃晚饭),其中起床和睡觉两种行为是固定的,看电视和吃晚饭两种行为是两个“挂钩”,具体的动作取决于“注册钩子”时传入的函数。