python—装饰器
定义:本质是函数,(装饰其他函数)就是为其他函数添加附加功能
原则:1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式
实现装饰器知识储备:
1.函数即“变量”
2.高阶函数
3.嵌套函数
高阶函数+嵌套函数=装饰器
初级版本:
用pycharm下断点 可以看出函数的运行过程!
机器运行过程
1.定义了 timer,test1,test2 3个函数
2.timer(test1) 执行函数timer(func),因为函数没有调用就往下走到了deco函数也没调用直接返回
3.test1 = timer(test1) 接上面的返回给了test1
4.test1() 调用deco函数体 先执行到 start_time=time.time()
然后执行func() 进入test1函数体 睡眠1秒 先后输出 in the test1
然后在执行 stop_time = time.time() -->print("the func run time is %s" %(stop_time-start_time))
1 # -*- coding:utf-8 -*- 2 import time 3 def timer(func): #timer(test1) func=test1 4 def deco(): 5 start_time=time.time() 6 func() #run test1() 7 stop_time = time.time() 8 print("the func run time is %s" %(stop_time-start_time)) 9 return deco 10 def test1(): 11 time.sleep(1) 12 print('in the test1') 13 def test2(): 14 time.sleep(1) 15 print('in the test2') 16 test1 =timer(test1) 17 test1()
进阶版:
1 import time 2 def timer(func): 3 def deco(): 4 start_time=time.time() 5 func() 6 stop_time = time.time() 7 print("the func run time is %s" %(stop_time-start_time)) 8 return deco 9 @timer # 这个就相当于上面的test1 = timer(test1) 10 def test1(): 11 time.sleep(1) 12 print('in the test1') 13 @timer # test2 = timer(test2) 14 def test2(): 15 time.sleep(1) 16 print('in the test2') 17 test1() 18 test2()
高级版:
1 import time 2 def timer(func): #timer(test1) func=test1 3 def deco(*args,**kwargs): 4 start_time=time.time() 5 func(*args,**kwargs) #run test1() 6 stop_time = time.time() 7 print("the func run time is %s" %(stop_time-start_time)) 8 return deco 9 @timer #test1=timer(test1) 10 def test1(): 11 time.sleep(1) 12 print('in the test1') 13 @timer # test2 = timer(test2) = deco test2(name) =deco(name) 14 def test2(name,age): 15 print("test2:",name,age) 16 test1() 17 test2("alex",22)
终极版:
1 import time 2 user,passwd = 'alex','abc123' 3 def auth(auth_type): 4 print("auth func:",auth_type) 5 def outer_wrapper(func): 6 def wrapper(*args, **kwargs): 7 print("wrapper func args:", *args, **kwargs) 8 if auth_type == "local": 9 username = input("Username:").strip() 10 password = input("Password:").strip() 11 if user == username and passwd == password: 12 print("\033[32;1mUser has passed authentication\033[0m") 13 res = func(*args, **kwargs) # from home 14 print("---after authenticaion ") 15 return res 16 else: 17 exit("\033[31;1mInvalid username or password\033[0m") 18 elif auth_type == "ldap": 19 print("搞毛线ldap,不会。。。。") 20 return wrapper 21 return outer_wrapper 22 def index(): 23 print("welcome to index page") 24 25 @auth(auth_type="local") # home = wrapper() 26 def home(): 27 print("welcome to home page") 28 return "from home" 29 @auth(auth_type="ldap") 30 def bbs(): 31 print("welcome to bbs page") 32 index() 33 print(home()) #wrapper() 34 bbs()
用pycharm下断点慢慢看
浙公网安备 33010602011771号