装饰器:本质是函数
功能:(装饰其他函数)就是为其他函数添加附加功能
原则: 1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式
实现装饰器知识储备:
1,函数即“变量"
2·高阶函数:
a:把一个函数名当做实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
b:返回值中包含函数名(不修改函数的调用方式)
3,高阶函数+嵌套函数=装饰器
import time
def timer(func):
print("x1")
def deco(*args,**kwargs):
print("x2")
start_time = time.time()
back = func(*args,**kwargs)
stop_time = time.time()
print("The run time of func is %s " % (stop_time - start_time))
return back
return deco
@timer # test1 = timer(test1)
def test1():
time.sleep(1)
print("in the test1")
@timer #test2 = timer(test2)
def test2(name,age):
time.sleep(1)
print("in the test2 is %s and %s"%(name,age))
return "I "
test1()
#print(test2("Huan",22))
#print("\033[33;1m xxxxxx \033[0m")
程序运行过程:
首先声明函数 timer,而后遇到@timer后,会走进函数timer。而后执行print("x1"),并且声明内部函数deco,但是不执行,返回deco使test1 = deco,等到调用test1()的时候,其实是调用了timer里的deco。实现了不修改源代码,不改变源代码的调用方式。