装饰器

装饰器就是用来为被装饰对象添加新功能的工具

装饰器是任意可调用对象,被装饰对象也是任意可调用对象

装饰器开放封闭原则:

封闭指的是对被装饰对象源代码修改的封闭,开放是对扩展功能的开放

装饰器的实现必须遵守量大原则:

1.不修改被装饰对象的源代码

2.不修改被装饰对象的调用方式

装饰器语法糖:

在被装饰对象的正上方单独一行写@装饰器的名字

装饰器语法糖的运行原理:

python解释器一旦运行到@装饰器的名字,就会调用装饰器,然后将被装饰函数的内存地址当做参数传给装饰器,最后将装饰器的结果赋值给原函数名

import time

# 装饰器模板
def outter(func):
def wrapper(*args,**kwargs):
#在调用函数前加功能
res=func(*args,**kwargs) #调用被装饰的也就是最原始的那个函数
#在调用函数后加功能
return res
return wrapper

@outter #index=outter(index) #index=wrapper
def index():
print('welcome to index page')
time.sleep(3)

index()


# 有参装饰器的模板
def outter1(x,y,z):
def outter2(func):
def wrapper(*args,**kwargs):
res=func(*args,**kwargs)
return res
return wrapper
return outter2

# 无参装饰器的模板
def outter(func):
def wrapper(*args,**kwargs):
res=func(*args,**kwargs)
return res
return wrapper

原文地址:https://www.cnblogs.com/fushaunglin/p/9440258.html