装饰器的演变过程:
例.实现一个函数测试电脑的读取速度并花了多少时间
1 import time 2 def gettime(arg): 3 starttime=time.time() 4 arg() 5 endtime=time.time() 6 print(endtime-starttime) 7 8 def go(): 9 lastnume=010 for i in range(100000000):11 lastnume+=112 print(lastnume)13 gettime(go)
装饰器本质: 装饰器=函数接口+嵌套函数
原则:1.不能修改被装饰函数的源码 2.不能修改被装饰函数的调用方式
作用:为其他函数添加附加功能
1 # 装饰器 2 def gettime(arg): 3 "函数接口用于封装函数" 4 def warpper(*args,**kwargs): 5 "用于返回实现的功能" 6 starttime=time.time() 7 arg() 8 endtime=time.time() 9 print(endtime-starttime)10 return warpper11 12 @gettime 13 def go():14 lastnume=015 for i in range(100000000):16 lastnume+=117 print(lastnume)18 go()
登陆系统:
1 user,passwd = 'Temu','etc123123' 2 def auth(auth_type): 3 print("auth func:",auth_type) 4 def outer_wrapper(func): 5 def wrapper(*args, **kwargs): 6 print("wrapper func args:", *args, **kwargs) 7 if auth_type == "local": 8 username = input("Username:").strip() 9 password = input("Password:").strip()10 if user == username and passwd == password:11 print("\033[32;1mUser has passed authentication\033[0m")12 res = func(*args, **kwargs) # from home13 print("---after authenticaion ")14 return res15 else:16 exit("\033[31;1mInvalid username or password\033[0m")17 elif auth_type == "admin":18 username = input("Username:").strip()19 password = input("Password:").strip()20 if user == username and passwd == password:21 print("\033[33;1mUser has passed authentication\033[0m")22 res2 = func(*args, **kwargs) # from home23 print("---after authenticaion ")24 return res225 else:26 exit("\033[31;1mInvalid username or password\033[0m")27 return wrapper28 return outer_wrapper29 30 System=["Windows","Unix"]31 print(System[0].center(20," "),System[1].center(20," "))32 33 while True:34 User_coice=input("请选择你要登陆的系统:")35 if User_coice == "Windows":36 @auth(auth_type="admin") # windows37 def pcwin():38 print("*******Hello,Welcome to Windows page*******")39 pcwin()40 break41 42 elif User_coice == "Unix":43 @auth(auth_type="local") # unix44 def home():45 print("Welcome to Home page")46 return "from home"47 print(home())48 break49 else:50 print("没有你要登陆的操作系统,请重新选择...")