ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 概述 装饰器本身是一个函数,用于装饰其他函数和类。 > **函数装饰器**在函数定义的时候进行名称重新绑定,提供一个逻辑层来管理函数和方法或随后对他们调用。 函数装饰器,增强被装饰 函数的功能,实现函数在不同环境的复用 。 > **类装饰器**在类定义的时候进行名称重新绑定,提供一个逻辑层来管理类或管理随后调用它们所创建的实例。 ### 应用 有切面需求的插入日志,性能测试,事务处理 ### 举例 ```python def deco(func): def wrapper(x): print "Say >>>." func(x) print "end..." return wrapper @deco def show(x): print x ``` ```python show('hiyang') Say >> >. hiyang end... ``` 图示说明 ![](http://qiniu.echosoul.cn/17-9-1/67538842.jpg) * 不带参数,不带返回值 ![](http://qiniu.echosoul.cn/dec.gif) * 带参数,不带返回值 ![](http://qiniu.echosoul.cn/dec2.gif) * 带参数,带返回值 ![](http://qiniu.echosoul.cn/dec3.gif) ## 带参数的装饰器 ~~~python # 进化前 def tips(func): def process(a, b): print("calculate start...") func(a, b) print("calculate stop...") return process @tips def add(a, b): print(a+b) @tips def sub(a, b): print(a-b) add(1, 2) sub(1, 2) ~~~ ~~~ python # 进化后 def enhance_tips(method): def tips(func): def process(a, b): print("calculate %s start..." % method) func(a, b) print("calculate %s stop..." % method) return process return tips @enhance_tips("add") def add(a, b): print(a+b) @enhance_tips("sub") def sub(a, b): print(a-b) add(1, 2) sub(1, 2) ~~~