Python装饰器实现注册回调函数功能的原理

Python装饰器实现注册回调函数功能的原理

decorator的常规用法

想要了解decorator如何实现注册回调函数功能的,需要先了解decorator的常规使用方法。
先看一段代码:




import sys  

def decorator(func):
    print('line:',sys._getframe().f_lineno)
    #定义新函数的具体功能
    def wrapper():
        #实现新功能,打印传入函数的函数名
        print('call %s():' % func.__name__)
        #原函数的功能
        return func()
    print('line:',sys._getframe().f_lineno)
    return wrapper

print('line:',sys._getframe().f_lineno)
@decorator
def decorator_test():
    print('this is decorator_test')
print('line:',sys._getframe().f_lineno)    

decorator_test()

执行结果如下:

./test.py
line: 17
line: 7
line: 14
line: 21
call decorator_test():
this is decorator_test

直接讲原理,可根据打印自行印证,原理很简单,代码从第15行开始执行,执行内容相当于:
decorator_test = decorator(decorator_test )
可以理解为,让decorator_test 指向(表示)decorator函数返回的函数,而decorator函数的参数即为decorator_test 。
这么做的目的:
1、通过将被修饰函数decorator_test 传入decorator函数,可以使decorator函数在完成新增功能后,不遗漏原本的decorator_test 函数功能。
2、decorator_test 指向decorator返回的新函数后,再次调用decorator_test ,即调用了包含decorator新功能和decorator_test 原功能的新函数。

decorator实现回调函数注册

在了解了decorator的常规用法后,发现在使用了@decorator后,代码会先进入第7行的decorator函数中,同时,我们也能在decorator中拿到原函数decorator_test ,故可使用decorator函数完成对decorator_test 进行回调函数的注册。
代码如下:

class TestClass(object):
    def __init__(self):
        self.fun = 0
        
    def decorator(self,fun):
        #通过fun变量实现对传入函数的回调
        self.fun = fun
        #仅注册回调函数,将原函数返回,不执行原函数工鞥呢,不改变原函数功能
        return fun
test = TestClass()

#将decorator_test函数传入test的decorator函数,并执行decorator函数
@test.decorator
def decorator_test():
    print('this is decorator_test')

#通过test的fun变量回调decorator_test函数
test.fun();

若需要将不同的回调函数分开注册,可在装饰器中添加参数,并在对应的函数中进行处理:

class TestClass(object):
    def __init__(self):
        self.fun_A = 0
        self.fun_B = 0
        
    def decorator(self,type):
        def wrapper(func):
            if type == 'A':
                self.fun_A = func
            if type == 'B':
                self.fun_B = func
            return func
        return wrapper


test = TestClass()

@test.decorator('A')
def decorator_test():
    print('this is decorator_test A')

@test.decorator('B')
def decorator_test():
    print('this is decorator_test B')

test.fun_A ();
test.fun_B ();

此时@test.decorator(‘A’)的调用方法等于:
decorator_test = decorator(‘A’)(decorator_test )

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值