装饰器 为多个函数加上认证功能(账号密码来源于文件),要求只要登陆成功一次,后续函数则无需登陆。

 1 dic = {                  
 2     'username':None,
 3     'status':False     #定义一个字典  status : False  为了改变函数执行的方向。
 4 }
 5 
 6 
 7 def wrapper(f):
 8     def inner(*args,**kwargs):
 9         if dic['status'] == True:     #若 status = True 则直接执行函数无需再次认证。
10             ret = f(*args,**kwargs)
11             return ret
12         else:
13             i = 0    
14             while i<3:   #   三次登录功能
15                 username = input('请输入你的用户名:').strip()
16                 password = input('请输入你的密码:').strip()
17                 with open('log1',encoding='utf-8') as f1:
18                     for j in f1:
19                         j_li = j.strip().split()
20                         if username == j_li[0] and password == j_li[1]:
21                             dic['username'] = username   #改变字典里的 username
22                             dic['status'] = True        #改变status 的 bool 值 为了改变下次函数进入的方向。
23                             ret = f(*args,**kwargs)
24                             return ret
25                     else:
26                         print('账号或密码错误,你还有%d次机会请重新输入...' % (2-i))
27                         i += 1
28     return inner
29 @wrapper
30 def article():
31     print('文章')
32 @wrapper
33 def diary():
34     print('日记')
35 @wrapper
36 def comment():
37     print('评论')
38 @wrapper
39 def file():
40     print('文件')
41 article()
42 diary()
43 comment()
44 file()
原文地址:https://www.cnblogs.com/stfei/p/8710452.html