用裝飾器做一個登陸功能(進階):
阿新 • • 發佈:2018-04-03
read AD OS pos 商城 *args readline wrapper 改變
1 dic = { 2 ‘username‘:None, 3 ‘status‘:False 4 } 5 def login(flag): # 傳入 ‘微信‘,‘QQ‘ 6 def wrapper(f): 7 def inner(*args,**kwargs): 8 if dic[‘status‘] == True: 9 ret = f() 10 return ret 11 else: 12 i = 013 while i < 3: 14 username = input(‘請輸入你的%s賬號:‘ % (flag)).strip() 15 password = input(‘請輸入你的%s密碼:‘ % (flag)).strip() 16 with open(‘login_msg‘,encoding=‘utf-8‘) as f1: 17 content = eval(f1.readline()) #eval() 將文件中的內容直接取出賦值給content 18 if username == content[flag][‘username‘] and password == content[flag][‘password‘]: #falg 的目的就是接受傳入的內容是‘微信‘還是‘QQ‘ 19 print(‘登陸成功‘) 20 dic[‘username‘] = username 21 dic[‘status‘] = True #改變狀態 22 ret = f() 23 return ret 24 else: 25 print(‘你輸入的賬號或密碼錯誤,你還有%d次機會,請重新輸入...‘ % (2-i)) 26 i += 1 27 return inner 28 return wrapper 29 @login(‘微信‘) 30 def taobao_home(): 31 print(‘淘寶首頁‘) 32 @login(‘微信‘) 33 def taobao_shop(): 34 print(‘淘寶商城‘) 35 @login(‘qq‘) 36 def jingdong_home(): 37 print(‘京東首頁‘) 38 @login(‘qq‘) 39 def jingdong_shop(): 40 print(‘京東商城‘) 41 42 choice_list = { #定義一個choice_list 用數字作key 函數名作值。 43 1:taobao_home, 44 2:taobao_shop, 45 3:jingdong_home, 46 4:jingdong_shop 47 } 48 49 while True: 50 print(‘1\t淘寶首頁\n2\t淘寶商城\n3\t京東首頁\n4\t京東商城‘) #循環打印四個內容 51 choice = input(‘請輸入你的選項:‘).strip() 52 if choice.isdigit(): 53 choice = int(choice) 54 if 0 < choice <= len(choice_list): 55 choice_list[choice]() # 通過選擇的數字 執行相應的函數 56 else: 57 print(‘你輸入的不在選項範圍內,請重新輸入...‘) 58 else: 59 print(‘你輸入的不是數字,請重新輸入...‘)
用裝飾器做一個登陸功能(進階):