1.装饰器的概念
装饰器是一个闭包:
内层函数引用外层函数的变量(参数也算变量),然后返回内层函数,就是闭包。
装饰器的本质还是函数
装饰器的基本用法:
1.定义一个装饰器函数(也可以用类)
2.定义业务函数(类)
3.用装饰器装饰器业务函数
2.打印日志
def log(func):
def wrapper(*args, **kwargs):
print(f'{func.__name__}函数开始执行了')
func(*args, **kwargs)
print(f"{func.__name__}函数执行结束了")
return wrapper
@log
def add(x, y):
return x + y
add(1, 2)
执行结果:
add函数开始执行了
add函数执行结束了
3.记录函数执行时间
import time
def log(func):
def wrapper(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
end_time = time.time()
total_time = end_time - start_time
print(f'函数{func.__name__}总共耗时{total_time}s')
return wrapper
@log
def add(x, y):
time.sleep(5)
return x + y
add(1, 2)
执行结果:
函数add总共耗时5.000309467315674s
4.带参的装饰器
def shout(category):
def decorator(func):
def wrapper(*args, **kwargs):
if category == 'dog':
print('a dog is shouting')
elif category == 'cat':
print('a cat is shouting')
else:
return
func(*args, **kwargs)
return wrapper
return decorator
@shout('dog')
def dog():
print('this is a dog')
@shout('cat')
def cat():
print('this is a cat')
dog()
cat()
执行结果:
a dog is shouting
this is a dog
a cat is shouting
this is a cat
5.类装饰器
class Logger(object):
def __init__(self, level='INFO'):
self.level = level
def __call__(self, func):
def wrapper(*args, **kwargs):
print(f"[{self.level}]:function {func.__name__}() is running")
result = func(*args, **kwargs)
return result
return wrapper
@Logger('WARNING')
def add(x, y):
return x + y
print(add(1, 2))
执行结果:
[WARNING]:function add() is running
3