无参数的装饰器
def welcome(fn):
def wrapper(*args, **kwargs):
print("welcome")
x = fn(*args, **kwargs)
return x
return wrapper
@welcome
def hello(name: str):
return f"hello %s" % name
print(hello("java"))
输出:
welcome
hello java
有参数的装饰器
def welcome(name: str):
def hh(fn):
def wrapper(*args, **kwargs):
print(f"welcome %s" % name)
x = fn(*args, **kwargs)
return x
return wrapper
return hh
@welcome("python")
def hello(name: str):
return f"hello %s" % name
print(hello("java"))
输出
welcome python
hello java