#装饰器本质是函数,用来装饰其他函数,也就是为其他函数添加附加功能
1)不能修改被装饰的函数的源码
2)不能修改被装饰的函数的调用方式
3)高阶函数+嵌套函数 =》装饰器
#高阶函数在定义
1)把一个函数名当作实参传给另外一个函数(不修改被装饰函数源代码的情况下为其添加功能)
2)返回值中包括函数名(不修改函数的调用方式)

#高阶函数+嵌套函数 =》装饰器 def timmer(func): #将函数作为参数被调用 def warpper(*args,**kwargs): start_time= time.time() func() ###该步骤调用test1() stop_time = time.time() print('the function run time is %s'%(stop_time-start_time)) return warpper @timmer # 也等同于test1 = timmer(test1) def test1(): time.sleep(0.21) print("It's test1") test1() #函数调用装饰器
函数嵌套
在一个函数体内用def去申明一个新函数,而不是去调用。

print(" 利用嵌套函数写装饰器 ") def timer(func): #time(test1) func = test1 def deco(*args,**kargs): #装饰器定义非固定参数 start_time = time.time() func(*args,**kargs) #run test1 stop_time = time.time() print("The function run time is %s"%(start_time - stop_time)) return deco @timer # test1 = timer(test1) #test1传给timer中的func def test1(): time.sleep(1) print("in the function test1") #test1 = timer(test1) #指针 test1() @timer def test2(name,age): time.sleep(1) print("in the function test2!!",name,age) #test2 = timer(test2) #指针 test2("yyw",22)

###利用嵌套函数写装饰器 import time user,pwd = "yyw","123" def auth(auth_type): print("auth type",auth_type) def outer_wrapper(func): print("outter wrpper") #print("outter wrpper", func)出错 def wrapper(*args,**kargs): print("outter wrpper", *args, **kargs) if auth_type == "local": _user = input("Username>>>:").strip() _pwd = input("Password>>>").strip() if user ==_user and pwd ==_pwd: print("