一、装饰器是什么?
装饰器,顾名思义,就是增强函数或类的功能的一个函数,装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,比如附加一个描述,附加一个执行时间。装饰器的返回值也是一个函数对象。
二、装饰器的分类
装饰器分函数装饰器和类装饰器。根据是否带参数分为无参装饰器和带参装饰器。
三、函数装饰器
1.函数无参装饰器
计算两个数的相加和相减的执行时间,代码如下:
#装饰器模式
import time
a=int(input('请输入一个整数:'))
b=int(input('请再输入一个整数:'))
def time_calc(func):
def wrapper(*args,**kargs):
start_time=time.time()
f=func(*args,**kargs)
exec_time=time.time()-start_time
print(func.__name__+'函数的执行时间是{}'.format(exec_time))
return f
return wrapper
@time_calc #语法糖
def add(a,b):
return a+b
@time_calc
def sub(a,b):
return a-b
print(add(a,b))
print(sub(a,b))
执行结果

说明:将计算函数的执行时间抽离出来,用装饰器来定义,在每个函数之前使用@语法糖,就可以使用装饰器进行装饰了
2.函数带参装饰器
输出函数的函数名,并输入日志级别为INFO,代码如下:
'''带参装饰器'''
def logging(level):
def wrapper(func):
def inner_wrapper(*args,**kwargs):
print('[{level}]: enter function {func}()'.format(level=level,func=func.__name__))
return func(*args,**kwargs)
return inner_wrapper
return wrapper
@logging(level='INFO') #用语法糖@引入装饰器logging
def say(something):
#print('say {}!'.format(something))
return something
#调用say方法
print(say('hello world!'))
执行结果:

四、类装饰器
'''类装饰器'''
class Decorator(object):
def __init__(self, f):
self.f = f
def __call__(self):
print("decorator start")
self.f()
print("decorator end")
@Decorator
def func():
print("func")
#调用方法func
func()
执行结果:

说明:__call__()是一个特殊方法,它可将一个类实例变成一个可调用对象:
p = Decorator(func) # p是类Decorator的一个实例 p() # 实现了__call__()方法后,p可以被调用
要使用类装饰器必须实现类中的__call__()方法,就相当于将实例变成了一个方法。
同一个函数可以使用多个装饰器语法糖@,只要在方法前使用语法糖@进行引入即可