python中装饰器的实现

装饰器是python的一个重要部分,作用是可以在不改变原函数功能的基础上来对原函数进行功能的升级。就像人穿衣服一样。。。

装饰器在python中的使用

在程序中通常通过@来进行装饰器的实现如:

def decorator_a(func):
    print ('Get in decorator_a')
    def inner_a(*args, **kwargs):
        print ('Get in inner_a')
        return func(*args, **kwargs)
    return inner_a
#@decorator_a
def f(x):
    print ('Get in f')
    return x * 2

以上代码实现了用函数decorator_a(func) 来装饰函数f() 运行f(1)后结果如图:
在这里插入图片描述
实现过程就相当于将函数f() 作为参数传入decorator_a(func) 函数,然后执行函数decorator_a(func) 返回的inner_a() 函数,如:

c = decorator_a(f)
c(1)

f() 作为参数传入decorator_a(fun) 将返回函数赋予c 然后执行c(1) 执行结果为:
在这里插入图片描述

多个装饰器实现原理

以单个装饰器类似,当一个函数拥有多个装饰器后,装饰器的装饰顺序为由里到外 来进行装饰。如:

def decorator_a(func):
    print ('Get in decorator_a')
    def inner_a(*args, **kwargs):
        print ('Get in inner_a')
        return func(*args, **kwargs)
    return inner_a
  
def decorator_b(func):
    print ('Get in decorator_b')
    def inner_b(*args, **kwargs):
        print ('Get in inner_b')
        return func(*args, **kwargs)
    return inner_b

@decorator_b
@decorator_a
def f(x):
    print ('Get in f')
    return x * 2

f(1)

函数f() 拥有@decorator_b 与 @decorator_a 两个装饰器,当执行f(1) 时,结果如下:
在这里插入图片描述
首先函数将f()作为参数进入执行装饰器decorator_a() 函数中的打印内容,然后返回inner_a函数,将inner_a 函数作为参数进入decorator_b()装饰器执行decorator_b() 中的打印并返回inner_b ,当运行f(1) 时,相当于运行了inner_b(1) 函数,执行里面的打印内容并运行传入的funcinner_a 函数,执行inner_a 中的打印然后执行装饰器decorator_a传入的参数funcf() 然后返回。当去掉上面例子中f() 函数的装饰器后改用函数调用的方式改写为参数调用的方式如下:

c = decorator_a(f)
d = decorator_b(c)
d(1)

执行结果如下:
在这里插入图片描述
以上就是我对python装饰器的一些理解,有错误的地方希望各位大牛多多指点。感谢

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白1.0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值