python 函数装饰器
# 使用一个函数来装饰另一个函数,不使用@ def a_new_decorator(a_func): def wrapTheFunc(): print("Do sth. before a_func()") a_func() print("Do sth. after a_func()") return wrapTheFunc def a_func_requiring_decoration(): print("I need some decoration") a_func_requiring_decoration = a_new_decorator(a_func_requiring_decoration) a_func_requiring_decoration()
# 输出如下: # Do sth. before a_func() # I need some decoration # Do sth. after a_func()
# 使用@来运行上面的代码 def a_new_decorator(a_func): def wrapTheFunc(): print("Do sth. before a_func()") a_func() print("Do sth. after a_func()") return wrapTheFunc @a_new_decorator def a_func_requiring_decoration(): print("I need some decoration") # a_func_requiring_decoration = a_new_decorator(a_func_requiring_decoration) a_func_requiring_decoration()
the @a_new_decorator is a just a short way of saying: a_func_requiring_decoration = a_new_decorator(a_func_requiring_decoration)
# 希望print(xx.__name__)的结果是xx,而不是wrapTheFunc # 使用functools.wraps来解决此问题 from functools import wraps def a_new_decorator(a_func): @wraps(a_func) def wrapTheFunc(): print("Do sth. before a_func()") a_func() print("Do sth. after a_func()") return wrapTheFunc @a_new_decorator def a_func_requiring_decoration(): print("I need some decoration") # a_func_requiring_decoration = a_new_decorator(a_func_requiring_decoration) a_func_requiring_decoration() print(a_func_requiring_decoration.__name__)
注意:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。
posted on 2021-04-07 11:15 Karlkiller 阅读(54) 评论(0) 编辑 收藏 举报
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步