@method_decorator() 源码解析
1 # coding:utf-8 2 """ 3 作用: 4 原理:闭包 >> 1. 函数内部定义函数 5 2.内部函数使用外部函数的变量 6 3.外部函数返回内部函数的引用 7 带参数的函数装饰器 》》 三层 8 9 类的装饰器 >> 解决self 参数的问题 10 >> 被装饰的对象是类不是函数 11 """ 12 13 14 def method_decorator(decorator, name=''): 15 print("类装饰器执行了") 16 17 def _dec(cls): 18 print("真正的类装饰器生成了,并执行了") 19 is_class = isinstance(cls, type) 20 if is_class: 21 method = getattr(cls, name) 22 else: 23 raise Exception("该装饰器只用来装饰类") 24 25 def _wrapper(self, *args, **kwargs): 26 @decorator 27 def bound_func(*args2, **kwargs2): 28 return method(self, *args2, **kwargs2) 29 30 return bound_func(*args, **kwargs) 31 32 setattr(cls, name, _wrapper) 33 return cls 34 35 return _dec 36 37 def my_decorator(bound_func): 38 print("函数装饰器执行了") 39 40 def real_func(*args, **kwargs): 41 print("\nexc decorator code before func\n") 42 ret = bound_func(*args, **kwargs) 43 print("\nexc decorator code after func\n") 44 return ret 45 46 return real_func 47 48 """ 49 @method_decorator(decorator=my_decorator, name="get") 50 ViewTemp = method_decorator(decorator=my_decorator, name="get")(ViewTemp) 51 ViewTemp = _dec(ViewTemp) 52 >>> ViewTemp.get = ViewTemp._wrapper 53 """ 54 55 @method_decorator(decorator=my_decorator, name="get") 56 class ViewTemp: 57 def get(self, request): 58 print("-----this is get method-----", "\nrequest==", request) 59 60 def post(self, request): 61 print("-----this is post method----") 62 63 if __name__ == '__main__': 64 """ 65 ViewTemp().get(request="xixixi) 66 ViewTemp()._wrapper(request="xixixi) 67 >>> _wrapper(self, request="xixixi) 68 >>> >>> @decorator my_decorator(bound_func) 69 >>> >>> def bound_func(*args2, **kwargs2): bound_func = real_func 70 return method(self, *args2, **kwargs2) 71 return bound_func(*args, **kwargs) 72 >>> real_func(request="xixixi) 73 >>> >>> print("\nexc decorator code before func\n") 74 >>> >>> ret = bound_func(request="xixixi") >> bound_func(request="xixixi") >> method(self, request="xixixi) 75 >>> >>> print("\nexc decorator code after func\n") 76 >>> >>> return ret 77 78 """ 79 ViewTemp().get(request="xixixi") 80 pass
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】