#装饰器:本质是函数,(装饰其它函数)就是为其他函数添加附加功能
#原则:1.不能修改被修饰的函数的源代码
# 2.不能修改被装饰的函数的调用方式
#实现装饰器知识储备:
# 1.函数即"变量"
# 2.高阶函数:
#a.把一个函数名当做实参传给另一个函数
#b.返回值中包含函数名
# 3.嵌套函数
#高阶函数+嵌套函数=》装饰器
装饰器案列:
import time def timer(func): #timer(test1) func=test1 def deco(*args,**kwargs): start_time = time.time() func(*args,**kwargs) #run test1() stop_time = time.time() print("the func run time is %s" % (stop_time - start_time)) return deco @timer #test1=timer(test1)= deco test1()=deco() def test1(): time.sleep(1) print("in the t1") @timer ##test2=timer(test2)= deco test2()=deco() def test2(name,age): time.sleep(3) print("test2",name,age) test1() test2("qjh",23)
原文:https://www.cnblogs.com/qjhh/p/12580544.html