python装饰器简介及同时使用多个装饰器的方法
作者:大数据老张
这篇文章主要介绍了python装饰器简介及同时使用多个装饰器的方法,python支持一个函数同时使用多个装饰器,本文结合实例代码给大家介绍的非常详细,需要的朋友可以参考下
python装饰器简介及同时使用多个装饰器
装饰器功能:
在不改变原有函数的情况下,唯已有函数添加新功能,且不改变函数名,无需改变函数的调用
特别适用于当多个函数需要添加相同功能时
python装饰器常用于以下几点:
- 登录验证
- 记录日志
- 检验输入是否合理
- Flask中的路由
什么是装饰器呢?装饰器如何使用?
# 声明装饰器
# 使用装饰器的函数,会自动将函数名传入func变量中
def decorator(func):
def wrapper():
# 在func()函数外添加打印时间戳
print(time.time())
# 调用func(),实际使用中,该func就是使用装饰器的函数
func()
return wrapper
# 使用装饰器
# 使用装饰器只需要在声明函数前加上 @装饰器函数名 即可
@decorator
def test():
print("this function' name is test")
# 使用装饰器
@decorator
def hello():
print("this function' name is hello")
test()
hello()
# 运行结果
1587031347.2450945
this function' name is test
1587031347.2450945
this function' name is hello如果使用装饰器的函数需要传入参数,只需改变一下装饰器函数即可
对上面的函数稍微修改即可
def decorator(func):
def wrapper(arg):
print(time.time())
func(arg)
return wrapper
@decorator
def hello(arg):
print("hello , ",arg)
hello('武汉加油!')
# 输出结果
1587031838.325085
hello , 武汉加油!
因为多个函数可以同时使用一个装饰器函数,考虑到各个函数需要的参数个数不同,可以将装饰器函数的参数设置为可变参数
def decorator(func):
def wrapper(*args,**kwargs):
print(time.time())
func(*args,**kwargs)
return wrapper
@decorator
def sum(x,y):
print(f'{x}+{y}={x+y}')
sum(3,4)
# 运行结果
1587032122.5290427
3+4=7python支持一个函数同时使用多个装饰器
同时使用多个装饰器时,需要调用的函数本身只会执行一次
但会依次执行所有装饰器中的语句
执行顺序为从上到下依次执行
def decorator1(func):
def wrapper(*args, **kwargs):
print("the decoretor is decoretor1 !")
func(*args, **kwargs)
return wrapper
def decorator2(func):
def wrapper(*args, **kwargs):
print("the decoretor is decoretor2 !")
func(*args, **kwargs)
return wrapper
@decorator1
@decorator2
def myfun(func_name):
print('This is a function named :', func_name)
myfun('myfun')因为 @decorator1 写在上面,因此会先执行decorator1 中的代码块,后执行decorator2 中的代码块
到此这篇关于python装饰器简介及同时使用多个装饰器的文章就介绍到这了,更多相关python多个装饰器使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
