装饰器应用练习
1.qq\weibo\weixin登陆认证
1 # 带参数的装饰器:(相当于开关)为了给装饰器传参 2 3 def login(s): 4 def outer(func): 5 def inner(*args, **kwargs): 6 if s == 'QQ': 7 print('login by QQ') 8 ret = func(*args, **kwargs) 9 elif s == 'wx': 10 print('login by wx') 11 ret = func(*args, **kwargs) 12 elif s == 'wb': 13 print('login by wb') 14 ret = func(*args, **kwargs) 15 else: 16 ret = func(*args, **kwargs) 17 return ret 18 return inner 19 return outer 20 21 @login('QQ') # login('QQ') = outer -> @outer -> f1 = outer(f1) 22 def f1(): 23 print('in f1\n') 24 25 @login('wx') # login('wx') = outer -> @outer -> f2 = outer(f2) 26 def f2(): 27 print('in f2\n') 28 29 @login('wb') # login('wb') = outer -> @outer -> f3 = outer(f3) 30 def f3(): 31 print('in f3\n') 32 33 f1() 34 f2() 35 f3()
2.编写装饰器,为多个函数加上认证功能(用户的账号密码来自文件),要求登陆成功后,后续的函数都无需再输入用户名及密码
1 # __author__ = "wyb" 2 # date: 2018/4/22 3 # 4 # 编写装饰器,为多个函数加上认证功能(用户的账号密码来自文件), 5 # 要求登陆成功后,后续的函数都无需再输入用户名及密码 6 import time 7 flag = True # flag为True未登录 8 9 10 # 打开文件将文件中的用户名和密码存入字典中 11 use_pwd = {} 12 with open("account.txt", "r") as f: 13 for line in f: 14 u, p = line.split(',') 15 use_pwd[u] = p.strip() 16 # print(use_pwd) 17 18 19 def login(login_type): 20 def wrapper(func): 21 def inner(*args, **kwargs): 22 global flag 23 if flag: 24 username = input("username: ") 25 password = input("password: ") 26 if use_pwd.get(username, None) == password: 27 print("Welcome, %s, and login by %s " % (username, login_type)) 28 func(*args, **kwargs) 29 flag = False 30 else: 31 print("用户名或密码错误!") 32 else: 33 func(*args, **kwargs) 34 return inner 35 return wrapper 36 37 38 @login('QQ') 39 def index(): 40 time.sleep(1) 41 print("Welcome to index") 42 43 44 @login('WX') 45 def home(): 46 time.sleep(2) 47 print("Welcome to home") 48 49 50 @login('WB') 51 def page(): 52 time.sleep(3) 53 print("Welcome to page") 54 55 56 page() 57 index() 58 home()
too young too simple sometimes native!