装饰器带参数

 1 user_list = [
 2     {'name':'alex','passwd':123},
 3     {'name':'xiaopang','passwd':123},
 4     {"name":'haha','passwd':1234}
 5 ]
 6 user_dic = {'user_name':None,"login":False}
 7 def auth(auth_type = 'sqlite'):
 8     def add_func(func):
 9         def wrapper(*args, **kwargs):
10             if auth_type == 'sqlite':
11                 print('登录类型为sqlite')
12                 if user_dic['user_name'] and user_dic['login']:
13                     res = func(*args, **kwargs)
14                     return res
15                 username = input("亲,请输入你的用户名: ").strip()
16                 passwd = input("请输入密码").strip()
17                 for i in user_list:
18                     if username == i['name'] and passwd == str(i['passwd']):
19                         user_dic['user_name'] = username
20                         user_dic['login'] = True
21                         res = func(*args, **kwargs)
22                         return res
23                 else:
24                     print("您输入的用户名或者密码错误")
25             elif auth_type == 'mysql':
26                 print('现在没学,不会')
27 
28         return wrapper
29     return add_func
30 @auth(auth_type='sqlite')  # 相当于先执行了auth(auth_type = 'sqlite')  然后返回函数名add_func; 就相当于@add_func
31 def index():
32     print('欢迎来到京东商城')
33 @auth(auth_type='sqlite')
34 def home(name):
35     print("%s 欢迎回到主页" % name)
36 @auth(auth_type='sqlite')
37 def shopping_car(name):
38     print('%s的购物车里面有[手机、电脑、汽车]'%name)
39 index()
40 home('liyulu')
41 shopping_car('liyulu')
42 输出:
43 登录类型为sqlite
44 亲,请输入你的用户名: sb
45 请输入密码123
46 您输入的用户名或者密码错误
47 登录类型为sqlite
48 亲,请输入你的用户名: alex
49 请输入密码123
50 liyulu 欢迎回到主页
51 登录类型为sqlite
52 liyulu的购物车里面有[手机、电脑、汽车]

 

posted @ 2020-02-28 19:55  竹石2020  阅读(190)  评论(0编辑  收藏  举报