- 执行环境是 Python3
- 当用多个装饰器修饰一个函数时,离函数定义最近的装饰器先被调用。
def make1(func):
def wrappe():
return "111" + func()
return wrappe
def make2(func):
def wrapped():
return "222" + func()
return wrapped
@make1
@make2
def hello():
return "hello world"
print(hello())
结果是:(先执行装饰器函数 make2,make2中的wrapped()函数返回值是 222hello world,然后再执行装饰器函数 make1,此时make1 的参数func函数传递的值就是 222hello world,此时 make1函数中的wrapped() 函数返回值就是111222hello world)
111222hello world
上面装饰器的另一种等价写法是:
# @make1
# @make2
def hello():
return "hello world"
hello = make1(make2(hello))
print(hello())
如有任何错误的地方,还请指正。