计算机基础,Python - 回调函数,使用装饰器注册回调函数

1. 参考:

  1. https://en.wikipedia.org/wiki/Callback_(computer_programming)
  2. https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
  3. https://stackoverflow.com/questions/824234/what-is-a-callback-function
  4. https://www.zhihu.com/question/19801131/answer/27459821

2. 概念:

  1. In computer programming, a callback is any executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at a given time.
  2. This execution may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback.
  3. 通俗来说,是将一个函数f1当作参数传给一个另外一个函数f2,f2在适合的时机调用f1。
  4. 回调函数优点是,程序可以在运行时,通过注册不同的回调函数,来决定、改变中间函数的行为。比简单的函数直接调用灵活

3. 例子1. 用Python实现基本的回调函数

3.1 callback function library

#回调函数1
#生成一个2k形式的偶数
def double(x):
    return x * 2
    
#回调函数2
#生成一个4k形式的偶数
def quadruple(x):
    return x * 4

3.2 接受回调函数的中间函数

#中间函数
#接受一个生成偶数的函数作为参数
#返回一个奇数
def getOddNumber(k, getEvenNumber):
    return 1 + getEvenNumber(k)
    
#起始函数,这里是程序的主函数
def main():    
    k = 1
    #当需要生成一个2k+1形式的奇数时
    i = getOddNumber(k, double)
    print(i)
    #当需要一个4k+1形式的奇数时
    i = getOddNumber(k, quadruple)
    print(i)
    #当需要一个8k+1形式的奇数时
    i = getOddNumber(k, lambda x: x * 8)
    print(i)
    
if __name__ == "__main__":
    main()

4. 例子2. 在Python中使用装饰器注册回调函数


class Test():

    # /**feature将调用callback(), 但是在Test中并没有真正的定义callback,
    # 而是等外部通过Test类的某个方法传入回调函数(这个行为叫注册回调函数)**/
    def feature(self):
        self.callback()

    def register_callback(self, func):
        self.callback = func
        return func


test = Test()


# /**将foo注册为回调函数**/
@test.register_callback
def foo():
    print('in foo()')


# /**调用feature将触发回调函数,可以在某个合适的时机调用**/
test.feature()

posted @ 2018-04-24 14:16  Rocin  阅读(1444)  评论(0编辑  收藏  举报