通用装饰器
通用装饰器
def wrapper(fun):
def inner(*args,**kwargs):
print(f"before execute target {fun} ")
ret=fun(*args,**kwargs)
print(f"after execute target {fun}")
return ret
return inner
@wrapper
def fun(*args,**kwargs):
print(args)
print(kwargs)
print("test")
return 1
if __name__=="__main__":
ret=fun(a=2,b=4)
print(ret)
带有参数的装饰器:
def wrapper_outer(name):
def wrapper(fun):
"""
:param fun: 被装饰的函数
:return: inner
"""
def inner(*args,**kwargs):
print(f"warpper_outer agrs is {name} ")
ret=fun(*args,**kwargs)
print(f"after execute target {fun}")
return ret
return inner
return wrapper
@wrapper_outer("user") #先执行函数的调用,函数返回一个装饰器,和@组合成语法糖,@wrapper
def fun(*args,**kwargs):
print(args)
print(kwargs)
return 1
if __name__=="__main__":
fun(a=2,b=4)