装饰器功能:
- 引入日志
- 函数执行时间统计
- 执行函数前预备处理
- 执行函数后清理功能
- 权限校验等场景
- 缓存
装饰器:
1 # 不带参数多装饰器 2 # 定义函数:完成包裹数据 3 def makeBold(fn): 4 def wrapped(): 5 return "<b>" + fn() + "</b>" 6 return wrapped 7 8 # 定义函数:完成包裹数据 9 def makeItalic(fn): 10 def wrapped(): 11 return "<i>" + fn() + "</i>" 12 return wrapped 13 14 # 先装饰离函数最近的,执行按照从上到下 15 @makeBold # 后被装饰 先执行 16 @makeItalic # 先被装饰 后执行 17 def test1(): 18 return "hello world-1" 19 20 print(test1()) 21 print("*" * 50) 22 23 # 带参数装饰器 24 from time import ctime, sleep 25 def timefun(func): 26 def wrapped_func(a, b): 27 print("%s called at %s" % (func.__name__, ctime())) 28 print(a, b) 29 func(a, b) 30 return wrapped_func 31 32 @timefun 33 def foo(a, b): 34 print(a+b) 35 36 foo(3,5) 37 sleep(2) 38 foo(1,4) 39 40 print("*" * 50) 41 42 # 不定长参数 43 def sum_num(func): 44 def sums(*args, **kwargs): 45 return func(*args, **kwargs) 46 return sums 47 48 @sum_num 49 def test2(a, b, c): 50 return a + b + c 51 52 print(test2(1, 2, 3)) 53 print("*" * 50) 54 55 # 装饰器带参数 56 URL_FUNC_DICT = dict() 57 58 def route(url): 59 def set_func(func): 60 URL_FUNC_DICT[url] = func 61 def call_func(): 62 route = "route:" + url + "----" + func() 63 return route 64 return call_func 65 return set_func 66 67 @route("/index.py") # "/index.py"传给了参数url 68 def index(): 69 return "index.html" 70 71 print("------路由------") 72 print(index()) 73 print("*" * 50) 74 75 from time import ctime, sleep 76 77 def timefun_arg(pre="hello"): 78 def timefun(func): 79 def wrapped_func(): 80 print("%s called at %s %s" % (func.__name__, ctime(), pre)) 81 return func() 82 return wrapped_func 83 return timefun 84 85 # 下面的装饰过程 86 # 1. 调用timefun_arg("itcast") 87 # 2. 将步骤1得到的返回值,即time_fun返回, 然后time_fun(foo) 88 # 3. 将time_fun(foo)的结果返回,即wrapped_func 89 # 4. 让foo = wrapped_fun,即foo现在指向wrapped_func 90 @timefun_arg("itcast") # 相当于 foo()==timefun_arg("itcast")(foo)() 91 def foo(): 92 print("I am foo") 93 94 @timefun_arg("python") 95 def too(): 96 print("I am too") 97 98 foo() 99 print("*" * 50) 100 101 # 类装饰器 102 class Test(object): 103 def __init__(self, func): 104 self.func = func 105 106 def __call__(self): 107 print("这里是装饰器添加的功能") 108 return self.func() 109 @Test # 相当于get_str = Test(get-str) 110 def get_str(): 111 return "haha" 112 113 print(get_str())
结果:
<b><i>hello world-1</i></b> ************************************************** foo called at Fri Sep 6 14:16:04 2019 3 5 8 foo called at Fri Sep 6 14:16:06 2019 1 4 5 ************************************************** 6 ************************************************** ------路由------ route:/index.py----index.html ************************************************** foo called at Fri Sep 6 14:16:06 2019 itcast I am foo ************************************************** 这里是装饰器添加的功能 haha 进程已结束,退出代码0