1、什么是装饰器
装饰指的是为其他事物添加额外的东西点缀
合到一起的解释:
装饰器指的定义一个函数,该函数是用来为其他函数添加额外的功能
2、为何要用装饰器
开放封闭原则 开放:指的是对拓展功能是开放的 封闭:指的是对修改源代码是封闭的
装饰器就是在不修改被装饰器对象源代码以及调用方式的前提下为被装饰对象添加新功能
需求:在不修改index函数的源代码以及调用方式的前提下为其添加统计运行时间的功能
def index(x,y):
time.sleep(3)
print('index %s %s' %(x,y))
index(111,222)
# index(y=111,x=222)
# index(111,y=222)
# 解决方案一:失败
# 问题:没有修改被装饰对象的调用方式,但是修改了其源代码
import time
def index(x,y):
start=time.time()
time.sleep(3)
print('index %s %s' %(x,y))
stop = time.time()
print(stop - start)
index(111,222)
# 解决方案二:失败
# 问题:没有修改被装饰对象的调用方式,也没有修改了其源代码,并且加上了新功能
# 但是代码冗余
import time
def index(x,y):
time.sleep(3)
print('index %s %s' %(x,y))
start=time.time()
index(111,222)
stop=time.time()
print(stop - start)
# 方案三的优化三:将wrapper做的跟被装饰对象一模一样,以假乱真
import time
def index(x,y,z):
time.sleep(3)
print('index %s %s %s' %(x,y,z))
def home(name):
time.sleep(2)
print('welcome %s to home page' %name)
def outter(func):
def wrapper(*args,**kwargs):
start=time.time()
res=func(*args,**kwargs)
stop=time.time()
print(stop - start)
return res
return wrapper
# 偷梁换柱:home这个名字指向的wrapper函数的内存地址
home=outter(home)
res=home('egon') # res=wrapper('egon')
print('返回值--》',res)
@用法
# 在被装饰对象正上方的单独一行写@装饰器名字
# @timmer # index=timmer(index)
def index(x,y,z):
time.sleep(3)
print('index %s %s %s' %(x,y,z))
# @timmer # home=timmer(ome)
def home(name):
time.sleep(2)
print('welcome %s to home page' %name)
index(x=1,y=2,z=3)
home('egon')