@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

 

posted on 2019-01-12 21:34 **勇敢的心 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lzc978/p/10261113.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值