1. 基本装饰器
1.1. 无参方法无参装饰器
# 无参log装饰器
def log(func):
def wrapper():
print('Log: excute method {}()'.format(func.__name__))
return func()
return wrapper
# 无参方法
@log
def do_save():
print('save something!')
# Log: excute method do_save()
# save something!
do_save()
1.2. 有参方法无参装饰器
利用(*args, **kwargs)
来表示任意参数。
此时若@log
则会出现异常,因为@log
装饰器的实现中并没有接收参数。
# 无参装饰器
def log_new(func):
def wrapper(*args, **kwargs):
print('Log: excute method {}()'.format(func.__name__))
return func(*args, **kwargs)
return wrapper
# 带参数的方法
# @log # TypeError need 1 argument
@log_new
def do_save_user(user):
print('save {}'.format(user))
# Log: excute method do_save_user()
# save JiangW
do_save_user('JiangW')
1.3. 有参方法有参装饰器
# 带参数的装饰器
def log_level(level):
def decorator(func):
def wrapper(*args, **kwargs):
print('Log[{}]: excute method {}()'.format(level, func.__name__))
return func(*args, **kwargs)
return wrapper
return decorator
@log_level('INFO')
def do_delete_user(user):
print('delete {}'.format(user))
# Log[INFO]: excute method do_delete_user()
# delete JiangW
do_delete_user('JiangW')
2. 基于类实现的装饰器
2.1. 简单基于类实现的装饰器
# 带参数
class LoggingLevel(object):
def __init__(self, level):
self.level = level
def __call__(self, func):
def wrapper(*args, **kwargs):
print('Log[{}]: excute method {}()'.format(self.level, func.__name__))
return func(*args, **kwargs)
return wrapper
@LoggingLevel('WARN')
def do_remove_user(user):
print('remove {}'.format(user))
# Log[WARN]: excute method do_remove_user()
# remove JiangW
do_remove_user('JiangW')
3. 注意事项
3.1. 拆分装饰器
利用@log_level
语法糖来实现的装饰器。
def log_level(level):
def decorator(func):
def wrapper(*args, **kwargs):
print('Log[{}]: excute method {}()'.format(level, func.__name__))
return func(*args, **kwargs)
return wrapper
return decorator
@log_level('INFO')
def do_delete_user(user):
print('delete {}'.format(user))
# Log[INFO]: excute method do_delete_user()
# delete JiangW
do_delete_user('JiangW')
拆分成每一步实际上最终为:
# 等同于
def do_delete_user(user):
print('delete {}'.format(user))
# # Log[INFO]: excute method do_delete_user()
# delete JiangW
decorator = log_level('INFO')
wrapper = decorator(do_delete_user)
wrapper('Jian111gW')
3.2. 函数名称改变
如3.1所述拆分装饰器后实际上最终是调用了
wrapper = decorator(do_delete_user)
wrapper('Jian111gW')
此时被@log_level
装饰器装饰的函数名已经变成了wrapper
print(do_delete_user.__name__) # wrapper
利用functools.wraps
来修正
def log_level(level):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print('Log[{}]: excute method {}()'.format(level, func.__name__))
return func(*args, **kwargs)
return wrapper
return decorator
@log_level('INFO')
def do_delete_user(user):
print('delete {}'.format(user))
print(do_delete_user.__name__) # do_delete_user
此时do_delete_user.__name__
为do_delete_user.