计算机基础,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()

转载于:https://www.cnblogs.com/allen2333/p/8929970.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值