目录
在不改变函数本身功能的情况下,对函数进行预处理,也就是在函数执行前或执行后,进行一些特殊的操作。临时添加一些功能,后期需要删除时,十分有用。
无输入参数,无返回值
被修饰的函数没有输入参数和返回值的用法。
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