python 入坑路--装饰器(语法糖)前戏1
一、装饰器定义
本质是函数,用来装饰其它函数,为其它函数添加新功能。
遵循的原则:1、不能修改被装饰函数的源代码。2、不能更改原函数的调用方式。(ps,在生产环境中,已定义好的函数,需要添加新功能,又不能做太多改动,所谓牵一发,而动全身。)
二、知识准备
- 函数即"变量"
- 高阶函数
- 嵌套函数
最终: 高阶函数+嵌套函数 => 装饰器
1、函数及“变量” :回顾变量的定义

函数亦是如此 
by the way :python 内存回收机制:1、内存计数器,就是当变量被一个门牌号引用,关于这个变量的内存地址计数器+1。当引用删除计数器-1
当没有没牌号引用“变量”-内存地址时(该地址的计数器0),回收机制发现后就将回收这块内存地址。
关于 del 内置方法:例如:x=1 del x,删除的只是 门牌号,既引用关系,并不清空内存地址, 也是等待内存回收机制,自动回收内存。
关于 python 解释性语言, 如下图中,在定义 test1函数时,引用了test2 函数,但是定义test1 时不会出错。
因为:定义仅仅是在内存中找一个位置存放函数体,并未真正执行。当条用test1,函数时,python 在内存中已经有两块内存函数体,所以可以正常执行。
如果 先调用 test1(),再定义test2 就已经来不及了,会报错。test2 没有定义。因为,python 自上而下解析代码,在执行test1() 时内存中还没有定义test2。
2.高阶函数,定义:a、把其它函数名作为参数传递进去函数中。b、把函数名做为返回值,return。满足这两条中的一条既为高阶函数。
1 import time #如下例子 是为高阶函数,实现了新增功能,但是改变了调用方式。把函数名作为一个参数传入函数中。 2 def bar(): 3 time.sleep(2) 4 print("in the bar") 5 6 7 def test(func): 8 start_t=time.time() 9 func() 10 stop_t=time.time() 11 print("func run time is {}".format(stop_t-start_t)) 12 13 print(test(bar)) 14 15 #输出入下 16 D:\python_51cto\venv1\Scripts\python.exe D:/python_51cto/day4/gjfunc.py 17 in the bar 18 func run time is 2.0001142024993896 19 None 20 21 Process finished with exit code 0
1 import time #如下例子,把函数名,当成返回值。但是结果仅仅是内存地址。仅仅,用高阶函数无法实现装饰器。 2 def bar(): 3 time.sleep(2) 4 print("in the bar") 5 6 def test2(func): 7 return func 8 9 print(test2(bar)) 10 11 #输入结果 12 D:\python_51cto\venv1\Scripts\python.exe D:/python_51cto/day4/gjfunc.py 13 <function bar at 0x0000000001E52E18> 14 15 Process finished with exit code 0

浙公网安备 33010602011771号