81python装饰器
业务多的话选择装饰器
- 实现原理:基于@语法和函数闭包,将原函数封装在闭包里,然后将函数赋值为一个新的函数(内层函数),执行函数时再在内层函数中执行闭包中的原函数。
- 实现效果:可以在不改变原函数内部代码 和 调用方式的前提下, 实现在函数执行和执行扩展功能。
- 适用场景:多个函数系统统一在 执行前后自定义一些功能。
装饰器实列:
# 装饰器实例 手写 def outer(origin): def inner(*args, **kwargs): # 执行前 res = origin(*args, **kwargs) # 执行后 return inner @outer def func(): pass func()
下面一步一步指导:看完就很简单了
引出:
def func(): print("我是func函数") value = (11, 22, 33, 44) return value def outer(origin): def inner(): print("before") res = origin() # 调用原来的func函数 print("after") return res return inner func = outer(func) result = func() print(result) # output: before 我是func函数 after (11, 22, 33, 44)
加装饰器一
""" @函数名 def xxx(): pass python内部会自动执行 函数名(xxx),执行完之后,再将结果赋值给 xxx xxx = 函数名(xxx) """ def outer(origin): def inner(): print("before") res = origin() # 调用原来的func函数 print("after") return res return inner @outer # func = outer(func) def func(): print("我是func函数") value = (11, 22, 33, 44) return value result = func() print(result) # output: before 我是func函数 after (11, 22, 33, 44)
加装饰器二
def outer(origin): def inner(): print("before") res = origin() # 调用原来的func函数 print("after") return res return inner @outer def func1(): print("我是func1函数") value = (11, 22, 33, 44) return value @outer def func2(): print("我是func2函数") value = (11, 22, 33, 44) return value @outer def func3(): print("我是func3函数") value = (11, 22, 33, 44) return value func1() func2() func3() # output: before 我是func1函数 after before 我是func2函数 after before 我是func3函数 after
优化
def outer(origin): def inner(*args, **kwargs): print("before") res = origin(*args, **kwargs) # 调用原来的func函数 print("after") return res return inner @outer def func1(a1): print("我是func1函数") value = (11, 22, 33, 44) return value @outer def func2(a1, a2): print("我是func2函数") value = (11, 22, 33, 44) return value @outer def func3(a1): print("我是func3函数") value = (11, 22, 33, 44) return value func1(1) func2(11, a2=22) func3(999) # output: before 我是func1函数 after before 我是func2函数 after before 我是func3函数 after
扩展一
# 扩展1 import functools def auth(func): @functools.wraps(func) def inner(*args, **kwargs): res = func(*args, **kwargs) # 执行原函数 return res return inner @auth def handler(): pass handler() print(handler.__name__) # handler ,如不加 @functools.wraps(func) 就返回的是inner这个函数名字
import functools def auth(func): @functools.wraps(func) def inner(*args, **kwargs): print("开始") res = func(*args, **kwargs) # 执行原函数 print("结束") return res return inner @auth def handler(): print("正在干活") handler() print(handler.__name__) # handler ,如不加 @functools.wraps(func) 就返回的是inner这个函数名字 # output 开始 正在干活 结束 handler
本文来自博客园,作者:__username,转载请注明原文链接:https://www.cnblogs.com/code3/p/17147764.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步