装饰器是什么?
装饰器的实质是函数,其作用是为被装饰的函数,在不改其功能的前提下,为其进行功能的拓展。
一、不带参数的装饰器:
def func(inner_func): a = 100 print("this is func") def wrapper(*args, **kwargs): print("this is inner_func") print(a) print(args, kwargs) inner_func(*args, **kwargs) return wrapper @func def ts(x, y): print("this is ts") print(x, y) ts(3, 4)
执行结果:
this is func this is inner_func 100 (3, 4) {} this is ts 3 4
我们可以看到,在ts()函数的基础上,实现了功能的拓展。
二、有参数的装饰器
有参数的装饰器,其实就是在无参数的装饰器上多加一层,用于参数传递
def decorator(m, n): def func(inner_func): a = 100 print("this is func") print(m, n) def wrapper(*args, **kwargs): print("this is inner_func") print(a) print(args, kwargs) print(m, n) inner_func(*args, **kwargs) return wrapper return func @decorator(150, 250) def ts(x, y, z=200, q="tom"): print("this is ts") print(x, y, z, q) ts(3, 4, z=999, q="jerry")
执行结果:
this is func 150 250 this is inner_func 100 (3, 4) {'z': 999, 'q': 'jerry'} 150 250 this is ts 3 4 999 jerry