本文實例講述了Python使用裝飾器模擬用戶登陸驗證功能。分享給大家供大家參考,具體如下:
# -*- coding:utf-8 -*-#!python3user_list = [ {'name':'ad1','passwd':'123'}, {'name':'ad2','passwd':'123'}, {'name':'ad3','passwd':'123'}, {'name':'ad4','passwd':'123'}]#初始狀態,用來保存登陸的用戶,client_dic = {'username':None,'login':False}#添加新功能def auth_func(func): def wrapper(*args,**kwargs): #參數檢查,判斷是否有用戶登錄,如果有,不用驗證,直接執行函數的功能 if client_dic['username'] and client_dic['login']: res = func(*args,**kwargs) return res #輸入用戶名和密碼 username = input('用戶名:').strip() passwd = input('passwd:').strip() #對比列表,檢查用戶名和密碼是否正確 for user_dic in user_list: if username == user_dic['name'] and passwd == user_dic['passwd']: client_dic['username'] = user_dic['name'] client_dic['login'] = True res = func(*args,**kwargs) return res else: print('用戶名或者密碼錯誤!') return wrapper@auth_funcdef index(): print("歡迎來到主頁")@auth_funcdef home(name): print("歡迎回家:%s"%name)@auth_funcdef shoppping_car(): print('購物車里有[%s,%s,%s]'%('奶茶','妹妹','娃娃'))print(client_dic)index()print(client_dic)home('root')
運行結果:
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答