PYTHON装饰器
学习要点:
一、本质是函数,(装饰其他函数)就是为其他函数添加附加功能。
装饰器原则
1、不能修改被装饰函数的源代码
2、不能修改在线运行或已编写代码的调用方式。
3、被装饰的函数对于装饰器完全透明,无法感知装饰器的存在。
代码演示如下:
import time
def timer(func):
def warpper(*args,**kwargs):
start_time=time.time()
func()
stop_time=time.time()
print ('the func run time is %s' %(stop_time-start_time))
return warpper
@timer
def test( ):
time.sleep(3)
print ('in the test1')
test()
运行结果:
E:\ProgramData\Anaconda3\python.exe E:/python/装饰器.py
in the test1
the func run time is 3.000171661376953
Process finished with exit code 0
装饰器知识领储备
1、函数即“”变量“”
2、高阶函数
1)将实参传递给形参运行。(在不修改源代码的基础上为其附加功能)
2)返回值当中包含函数名(不修改函数的调用方式)
3、嵌套函数
高阶函数+嵌套函数=〉可实现装饰器的效果
def a():
x=1
print (x)
def b():
x=2
print (x)
def c():
x=3
print (x)
c()
b()
a()
演示结果:
E:\ProgramData\Anaconda3\python.exe E:/python/装饰器.py
1
2
3
Process finished with exit code 0
马有失蹄之时,人有摔倒之日,只要不死终会踏着泥泞一路前行。