Python-decorator修饰器及@wraps的用法

目录

无输入参数,无返回值

有输入参数,无返回值

有输入参数,有返回值

参数数量和种类不固定

@wraps的作用


        在不改变函数本身功能的情况下,对函数进行预处理,也就是在函数执行前或执行后,进行一些特殊的操作。临时添加一些功能,后期需要删除时,十分有用。

无输入参数,无返回值

        被修饰的函数没有输入参数和返回值的用法。

import time

# 定义修饰函数
def time_cost(func):
    def wrap():
        t1 = time.time()
        func()
        _cost = time.time() - t1
        print(f"Cost {_cost}s")
        
    return wrap

# 使用修饰器修饰函数
@time_cost
def foo():
    time.sleep(1)

# 调用函数
foo()    # Cost 1.0128180980682373s

有输入参数,无返回值

        被修饰的函数有输入,没有返回值的用法。

import time

# 定义修饰函数
def time_cost(func):
    def wrap(x):
        t1 = time.time()
        func(x)
        _cost = time.time() - t1
        print(f"Cost {_cost}s")
        
    return wrap

# 使用修饰器修饰函数
@time_cost
def foo(x):
    print(f"Para si {x}")
    time.sleep(0.1)

# 调用函数
foo(5)

'''
Para si 5
Cost 0.10230612754821777s
'''

有输入参数,有返回值

        被修饰的函数有输入参数,有返回值

import time

# 定义修饰函数
def time_cost(func):
    def wrap(x, y):
        t1 = time.time()
        res = func(x, y)
        _cost = time.time() - t1
        print(f"Cost {_cost}s")
        return res
    return wrap

# 使用修饰器修饰函数
@time_cost
def foo(x, y):
    time.sleep(0.1)
    return x+y

# 调用函数
print(foo(5, 6))

'''
Cost 0.11413002014160156s
11
'''

参数数量和种类不固定

        被修饰的函数不确定输入参数的数量和类型(位置参数或关键字参数)

import time

# 定义修饰函数
def time_cost(func):
    def wrap(*arg, **karg):
        t1 = time.time()
        res = func(*arg, **karg)
        _cost = time.time() - t1
        print(f"Cost {_cost}s")
        return res
    return wrap

# 使用修饰器修饰函数
@time_cost
def foo(x, y, v1=123, v2=456):
    print(f"x is {x}")
    print(f"y is {y}")
    print(f"v1 is {v1}")
    print(f"v2 is {v2}")
    _sum = x + y + v1 + v2
    print(f"sum is {_sum}")
    
    return _sum

# 调用函数
print(foo(5, 6, v2=333))

'''
x is 5
y is 6
v1 is 123
v2 is 333
sum is 467
Cost 0.013482809066772461s
467
'''

@wraps的作用

        使用修饰器后,其实已经变成另一个函数了,从__name__属性可以看出来。

import time

# 定义修饰函数
def time_cost(func):
    def wrap():
        t1 = time.time()
        func()
        _cost = time.time() - t1
        print(f"Cost {_cost}s")
        
    return wrap

# 使用修饰器修饰函数
@time_cost
def foo():
    time.sleep(1)

# 打印__name__,可以看出来函数已经变成了wrap
print(foo.__name__)    # wrap

        使用@wraps后,不改变原有函数的结构(__name__)。

import time

# 定义修饰函数
def time_cost(func):
    @wraps(func)
    def wrap():
        t1 = time.time()
        func()
        _cost = time.time() - t1
        print(f"Cost {_cost}s")

    return wrap

# 使用修饰器修饰函数
@time_cost
def foo():
    time.sleep(1)

# 打印__name__,可以看出来函数已经变成了wrap
print(foo.__name__)    # foo

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值