python 装饰器
装饰器 顾名思义 就是一个用来修改其他函数的功能的函数。
def new_decorator(a_func): #装饰器函数
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
def function_requiring_decoration(): #被装饰的函数
print("I am the function which needs some decoration to remove my foul smell")
function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
function_requiring_decoration = new_decorator(function_requiring_decoration) #通过装饰器函数得到新函数功能
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
实际使用时 可以将 @装饰器函数 放在被装饰的函数前 来实现函数添加功能的方法。
@new_decorator
def function_requiring_decoration():
"""Hey you! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
# I am the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func()
#the @new_decorator is just a short way of saying:
function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
这样做修改之后会有一个问题: 函数名和注释文档会变成 装饰器中返回函数的名称与其对应的文档。
print(function_requiring_decoration.__name__)
# Output: wrapTheFunction
解决的方法:
使用functiontools 中的wraps函数
from functools import wraps
def a_new_decorator(a_func):
@wraps(a_func)
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
"""Hey yo! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration
装饰器应用实例:
日志:
from functools import wraps
def logit(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs) #需要返回被装饰的函数本身
return with_logging
@logit
def addition_func(x):
"""Do some math."""
return x + x
result = addition_func(4)
# Output: addition_func was called
print(result)
# Output: 8
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现