先看一段简单的装饰器代码
def outer(func):
def inner(*args):
print("****************")
func(*args)
return inner
@outer
def sum(x,y):
print(x+y)
sum(1,2)
这里@outer 表示给sum函数装饰,具体代码是sum = outer(sum)类似
def outer(func):
def inner(*args):
print("****************")
func(*args)
return inner
def sum(x,y):
print(x+y)
sum = outer(sum)
sum(1,2)
相当于outer内的func = sum,sum = inner
基本了解规则后可以考虑一下这个代码,详细运行过程在最后
注意多重装饰时会先执行近的装饰声明
def dec1(func):
print("1111")
def one():
print("2222")
func()
print("3333")
return one
def dec2(func):
print("aaaa")
def two():
print("bbbb")
func()
print("cccc")
return two
def dec3(func):
print("!!!!")
def three():
print("####")
func()
print("****")
return three
@dec1
@dec2
@dec3
def test():
print("test test")
test()
运行结果为
!!!!
aaaa
1111
2222
bbbb
####
test test
****
cccc
3333
原因
def dec1(func1): #10、第三步func1 =two
print("1111") #11、第三步 输出1111
def one(): #14执行这里
print("2222") #15输出这里
func1() #16、执行这里也就是 two()
print("3333") #最后输出这个
return one #12、将one返回给test 然后再执行test()最下面的执行语句
def dec2(func2): #6、第二步 func = three
print("aaaa") #7、第二步 输出aaaaaa
def two(): #17、执行到这里
print("bbbb") #18、输出
func2() #19、执行这里,也就是three()
print("cccc") #25、输出,然后返回到 func1 后面,因为从那过来的
return two #8、将two返回给test 然后执行@dec1
def dec3(func3): #2、第一步执行时func = test
print("!!!!") #3、第一步执行时输出
def three(): #20、执行这里
print("####") #21、输出
func3() #22、执行这里,也就是test()
print("****") #25、输出,然后返回到 func2 后面,因为从那过来的
return three #4、将three返回给test 然后执行@dec2
@dec1 #9、第三步: test = dec1(func1) = one(return返回的) func1 = test = two
@dec2 #5、第二步 test = dec2(func2) = two(return返回的) func2 = test = three
@dec3 #1、第一步 test = dec3(func3) = three(return返回的) func3 = test
def test(): #23、执行这里
print("test test") #24输出,返回到func3()后面,因为从那过来的
test() #13、执行到这里 执行因为test = one,执行one()函数