python 装饰器:同一个函数调用多个装饰器和嵌套函数调用一个装饰器
时间:2023-12-29 02:37:02
总结:内部先调用,外部后调用,实际上是函数返回机制:栈。
参考连接:
本文帮助您对装饰器有初步的了解
两个装饰器
from functools import wraps def decorator_name(a_func): @wraps(a_func) def wrapTheFunction(*args): print(a_func.__name__ "装饰1:执行前") a_func(*args) print(a_func.__name__ "的装饰器1:执行后") return wrapTheFunction def decorator_args(a_func): @wraps(a_func) def wrapTheFunction(*args): print(a_func.__name__ "装饰2:执行前") a_func(*args) print(a_func.__name__ "装饰2:执行后") return wrapTheFunction
同一个函数调用多个装饰器
@decorator_name @decorator_args def com_fun(*args): print("com_fun函数求和:",sum(args)) if __name__=="__main__": # 以下两个句子等价 com_fun(1,2) decorator_name(decorator_args(com_fun(1,2)))
执行com_fun()的结果:
嵌套函数调用同一个装饰器
内部的函数先被装饰器修饰,被外部的函数包围。
@decorator_name
def out_fun():
print("out_fun执行中")
inner_fun()
@decorator_name
def inner_fun():
print("inner_fun执行中")
执行out_fun()的结果: