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=7

python支持一个函数同时使用多个装饰器

同时使用多个装饰器时,需要调用的函数本身只会执行一次
但会依次执行所有装饰器中的语句
执行顺序为从上到下依次执行

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 中的代码块

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值