python装饰器

一、Python通用装饰器

 1 # -*- coding:utf-8 -*-
 2 
 3 def NormalFunctionDescript(func, *args, **kwargs):
 4     #do_something_with_or_without_these_parameters
 5     ...
 6     def inner(*args, **kwargs):
 7         #do_something_first
 8         ...
 9         ret = func(*args, **kwargs)
10         #do_something_last
11         return ret
12     #do_something_whih_or_without_these_parameters
13     ...
14     return inner

二、Python 装饰器详解

好久没有正经写过python代码了,今天由于一些需求,又用到了装饰器,才发现自己忘得差不多了,参考了别人的博客,复习了一把,这次把笔记记下来省的以后再次忘了。

下面是正式内容,就不扯淡了,后面的内容全部在代码框里了。

  

 1 #python 装饰器
 2 
 3 #####################################
 4 ##exp.1 简单装饰器和函数都无参数
 5 
 6 def description(func):
 7     print "do_something"
 8     func()
 9     print "do_something"
10     return func
11 
12 def work():
13     do_something()
14 
15 work = description(work)#装饰器修饰语句
16 
17 work()#引用
18 
19 ###使用语法糖@修饰
20 @description
21 def work():
22     do_something()
23 
24 #####################################
25 ##exp.2 使用内嵌函数保证每次装饰器都起效(上一中只在第一次调用起效)
26 
27 def description(func):
28     def _description():
29         print "do_something"
30         func()
31         print "do_something"
32     return _description
33 
34 @description
35 def work():
36     do_something()
37 
38 #####################################
39 ##exp.3 函数带参数的
40 
41 def description(func):
42     def _description(a,b):
43         print "do_something"
44         ret = func(a,b)
45         print "do_something"
46         return ret
47     return _description
48 
49 @description
50 def work(a,b):
51     do_something(a,b)
52 ###参数数量不确定时候
53 #a->*args    b->**kwargs
54 
55 #####################################
56 ##exp.e 装饰器带参数的
57 
58 def desc(a,b):
59     def _desc(func):
60         def __desc():
61             print a
62             ret = func()
63             print b
64             return ret
65         return __desc
66     return _desc
67 
68 @desc
69 def work()
70     do_something()
71 
72 #####################################
73 ##exp.e 装饰器带类参数的
74 
75 class locker:
76     def __init__(self):
77         print "init"
78     
79     @staticmethod
80     def acq(self):
81         print "acq"
82     @staticmethod
83     def rel(self):
84         print "rel"
85 
86 def desc(cls):
87     def _desc(func):
88         def __desc():
89             cls.acp()
90             func()
91             cls.rel()
92         return __desc
93     return _desc
94 
95 @desc(locker)
96 def work():
97     do_something()
原文地址:https://www.cnblogs.com/KevinGeorge/p/7784360.html