装饰器(Python)

理解装饰器之前需要理解的内容:
函数+闭包

装饰器

看了许多关于装饰器的解释,推荐菜鸟教程。
附上链接:https://www.runoob.com/w3cnote/python-func-decorators.html
装饰器的作用就是对现有的函数进行内容上的增加。如果原有函数的内容有需要增补的时候,就需要用到装饰器。
为了方便叙述,附上如下代码来自于菜鸟教程:

def a_new_decorator(a_func):
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction
 
def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell") 
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
 
a_function_requiring_decoration()

结果:

I am doing some boring work before executing a_func()
I am the function which needs some decoration to remove my foul smell
I am doing some boring work after executing a_func()

**注:**这里输出了三行是为了方便理解。
分析:

  • 我们首先实现了一个闭包,原因如下:
    我们想在原有的函数a_function_requiring_decoration中实现“装饰”–即添加新内容,并且前提是不能修改原来函数中的功能。该怎么办?
    闭包是一个很妙的选择,闭包通过外部函数的参数传递至函数中,这时内部函数就可以使用(这里需要清楚了解函数的机制)。
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

这一行代码就是装饰器的实现过程,将函数名作为参数传递至a_new_decorator内,然后再其内部wrapTheFunction函数中实行调用a_function_requiring_decoration,这里要明确:a_function_requiring_decoration就是被装饰的函数。wrapTheFunction可以理解为装饰品,最后惊喜的发现,上述代码执行完的那一刻,a_function_requiring_decoration就拥有了之前的功能和wrapTheFunction的功能。当然wrapTheFunction内部命令和a_function_requiring_decoration是由wrapTheFunction的编写来决定的。

最后:

@a_new_decorator

把上面这条代码放在def a_function_requiring_decoration上面就完成了对它的修饰。

Wonderful!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值