python3 装饰器

 

装饰器

定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能

 

原则:

1.不能修改被装饰的函数的源代码

2.不能修改被装饰的函数的调用方式

 

实现装饰器知识储备:

1.函数即“变量”

2.高阶函数

3.嵌套函数

高阶函数+嵌套函数=》装饰器

 

 

高阶函数

  1.把一个函数当做实参传给另外一个函数(不能修改被装饰函数源代码的情况下为其添加附加功能)

  2.返回值中包含函数名(不修改函数的调用方式)

 

import time

def timer(func): #timer(test1) func = test1
def deco(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
end_time = time.time()
print('the program excute time %s' %(end_time-start_time))
return deco

@timer #test1 = timer(test1)
def test1(name,age):
time.sleep(3)
print('print the test1',name,age)

@timer #test2 = timer(test2)
def test2():
time.sleep(3)
print('print the test2')

test1('xiaoming',18)
test2()

 

posted @ 2020-06-17 21:53  小猿_vv  阅读(157)  评论(0)    收藏  举报