使用场景
def decorator(func):
def wrapper(*args, **kwargs):
print("start ---")
func(*args, **kwargs)
print("--- end")
return wrapper
def greeting():
print('Hello')
greeting = decorator(greeting)
greeting()
# 输出
start ---
Hello
--- end
装饰器 ' @ ' 使用
def decorator(func):
def wrapper(*args, **kwargs):
print("start ---")
func(*args, **kwargs)
print("--- end")
return wrapper
@decorator
def greeting():
print('Hello')
greeting()
# 输出
start ---
Hello
--- end
带参数装饰器
def decorator(user):
def wrapper1(func):
def wrapper2(*args, **kwargs):
print("start ---")
func(*args, **kwargs)
print(user)
print("--- end")
return wrapper2
return wrapper1
@decorator(user="Jack")
def greeting():
print('Hello')
greeting()
# 输出
start ---
Hello
Jack
--- end
装饰器类
class decorator(object):
def __init__(self, user='Jack'):
self.user = user
def __call__(self, func):
def wrapper(*args, **kwargs):
print("start ---")
func(*args)
print(self.user)
print("--- end")
return func
return wrapper
@decorator(user="Jack")
def greeting():
print('Hello')
greeting()
# 输出
start ---
Hello
Jack
--- end
网友评论