代码语言:javascript复制
#定义装饰器,outer参数是函数,返回也是函数
#作用:在函数执行前和执行后分别附加额外功能
def outer(func):
def inner(*args, **kwargs):
print("log")
func(*args, **kwargs)
print("Don't back")
# return "r"
return inner
@outer
def f1(a):
print(a,"F1")
@outer
def f2(a,b):
print("F2",a,b)
f1(123)
f2(123,456)
#带参数的装饰器,在outer外边又包装了一层
def oo(arg):
print("hihihihi") #此处的代码,在装饰器被调用时就被执行,不需要等被装饰的函数被调用
def outer(func):
def inner(*args, **kwargs):
print(arg)
print("log")
func(*args, **kwargs)
print("Don't back")
print(arg)
# return "r"
return inner
return outer
def tt(func):
def inner(*args, **kwargs):
# print(arg)
print("aaaaa")
func(*args, **kwargs)
print("ttttt")
# print(arg)
# return "r"
return inner
@tt
@oo(123333) #可以多层装饰,规则是:从上到下执行装饰器
def f1(a):
print(a,"F1")
@oo(11111)
def f2(a,b):
print("F2",a,b)
#f1(123)
#f2(123,456)
结果:
hihihihi
hihihihi