函数装饰器可以修改其他函数的功能,可以让代码更加简介
函数装饰器可以将函数作为参数传给另一个函数
先写个例子
def hello(): return "hello" def everyone(function): print("everyone") print(function()) #执行 everyone(hello) #输出 everyone hello
再上一个例子中,已经创建了一个装饰器,现在我们再来修改一下
def decorator_first(function): def Inside_function(): print ("This is Inside_function_first") function() print("This is Inside_function_second") return Inside_function def decorator_second(): print ("This is Inside_function_third") #执行 decorator_second=decorator_first(decorator_second) decorator_second() #输出 This is Inside_function_first This is Inside_function_third This is Inside_function_second
或许会疑惑,代码中并没有@符号,那下面用@符号重塑一下上面的例子
@decorator_first(): def decorator_second(): print("This is Inside_function_third") #执行 decorator_second() #输出 This is Inside_function_first This is Inside_function_third This is Inside_function_second
要是我们运行如下代码时,会有个问题
#执行 print(decorator_second.__name__) #输出
Inside_function
这个输出应该为 decorator_second 这个函数被 Inside_function 替代了,我们可以用functools.wraps
from functools import wraps def decorator_first(function): @wraps(function) def Inside_function_first():
print ("This is Inside_function_first") function() print("This is Inside_function_second")
return Inside_function
@decorator_first
def decorator_second(): print("This is Inside_function_third")
现在就可以了