多层装饰器


# an example of python decorator
def deco1(func):
print(1)
def wrapper1():
print(2)
func()
print(3)
print(4)
return wrapper1

def deco2(func):
print(5)
def wrapper2():
print(6)
func()
print(7)
print(8)
return wrapper2

def deco3(func):
print(9)
def wrapper3():
print(10)
func()
print(11)
print(12)
return wrapper3

@deco1
@deco2
@deco3
def foo():
print('foo')


if __name__ == '__main__':
foo()





执行结果:

9
12
5
8
1
4
2
6
10
foo
11
7
3

Process finished with exit code 0

 

执行函数相当于:deco1(deco2(deco3(foo)))

像剥洋葱一样,一层一层的

posted @ 2020-11-17 14:23  一只有梦想的咸鱼  阅读(73)  评论(0编辑  收藏  举报