码迷,mamicode.com
首页 > 编程语言 > 详细

python_20_装饰器_高阶函数的使用_01

时间:2018-09-20 22:18:49      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:opp   app   and   code   手机   函数   put   字典   删除   

登陆验证代码.

 1 #用户验证功能,不修改源代码,使用装饰器。
 2 user_dic={username:None,login:False}  #定义全局变量
 3 
 4 def auth_func(func):
 5     def wrapper(*args,**kwargs):
 6         if user_dic[username] and user_dic[login]:
 7             res = func(*args, **kwargs)
 8             return res
 9         user_name = input(用户名:).strip()  #删除首尾空格
10         pass_wd = input(用户密码:).strip()
11         if user_name == w and pass_wd == 123:
12            user_dic[username] = user_name
13            user_dic[login] = True
14            res = func(*args, **kwargs)
15            return res
16         else:
17             print(用户名或密码输入错误)
18 
19     return wrapper
20 
21 @auth_func
22 def index():
23   print(1234564897)
24   return 5
25 
26 @auth_func
27 def home(name):
28     print(%s欢迎回家%name)
29 @auth_func
30 def shopping_car(name):
31     print(%s购物车里面有【%s,%s,%s】%(name,手机,笔记本,数码相机))
32 
33 index()
34 
35 home(123)
36 shopping_car(产品经理)
 1 user_list=[
 2     {name:alex,passwd:123},
 3     {name:linhaifeng,passwd:456},
 4     {name:wupeiqi,passwd:789},
 5     {name:yuanhao,passwd:123},
 6 ]
 7 # for user_dic in user_list:    #遍历列表字典
 8 #    # print(user_dic.keys(),user_dic.values())
 9 #     a = user_dic[‘name‘]
10 #     b = user_dic[‘passwd‘]
11 #     print(a)
12 #     print(b)
13 
14 #用户验证功能,不修改源代码,使用装饰器。
15 current_dic={username:None,login:False}  #定义全局变量
16 
17 def auth_func(func):
18     def wrapper(*args,**kwargs):
19         if current_dic[username] and current_dic[login]:
20             res = func(*args, **kwargs)
21             return res
22 
23         user_name = input(用户名:).strip()  #删除首尾空格
24         pass_wd = input(用户密码:).strip()
25 
26         for user_dic in user_list:           #遍历列表字典(字典包含账号,密码)
27             if user_name == user_dic[name] and pass_wd == user_dic[passwd]:
28                 current_dic[username] = user_name       #保存全局变量
29                 current_dic[login] = True                #保存全局变量
30                 res = func(*args, **kwargs)
31                 return res
32         else:
33             print(用户名或者密码错误)
34 
35     return wrapper
36 
37 @auth_func
38 def index():
39   print(1234564897)
40   return 5
41 
42 @auth_func
43 def home(name):
44     print(%s欢迎回家%name)
45 
46 @auth_func
47 def shopping_car(name):
48     print(%s购物车里面有【%s,%s,%s】%(name,手机,笔记本,数码相机))
49 
50 index()
51 print(用户---,current_dic)
52 home(123)
53 print(用户---,current_dic)
54 shopping_car(产品经理)

 

python_20_装饰器_高阶函数的使用_01

标签:opp   app   and   code   手机   函数   put   字典   删除   

原文地址:https://www.cnblogs.com/TomorrowOFFaith/p/9683610.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!