python 入坑路--裝飾器(語法糖)--高高潮
阿新 • • 發佈:2018-01-01
wrapper else clas inpu 參數 index word com oca
上回我們說到,傳入的函數帶參數,這回我們要說的是,裝飾器帶參數,那麽裝飾器要如何是好。
1 u_n="keven" 2 passwd="abc123" 3 4 def auth(auth_type): 5 def outer_wrapper(func): 6 def wrapper(*args,**kwargs): 7 print(*args,**kwargs) 8 username=input("pls input your username:").strip() 9 passwrod=input("pls input your password:").strip() 10 if auth_type=="local": 11 if username== u_n and passwrod==passwd: 12 print("\033[5;40m user has pass authentication \033[0m") #給字體加顏色,裝X 13 res=func() 14 print("after authentication") #w為了驗證 函數執行後,能否將函數結果返回。 15 return res 16 else: 17 print("Invalid passwrod or username") 18 elif auth_type == "ldap": 19 print("先這樣子,太復雜,老師沒演示我也不懂") 20 pass 21 22 return wrapper #確實記一定不能有括號,用pycharm 自動補全一直會帶括號,坑。23 return outer_wrapper 24 25 26 def index(): 27 print("welcome to the index") 28 29 @auth(auth_type="local") #裝飾器帶參數 30 def home(): 31 print("welcome to the home") 32 33 @auth(auth_type="ldap")#裝飾器帶參數 34 def bbs(): 35 print("welcome to the bbs") 36 37 38 index() 39 home() 40 bbs()
python 入坑路--裝飾器(語法糖)--高高潮