装饰器版一:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| msg = """ 1.请登录 2.请注册 3.进入文章页面 4.进入评论页面 5.进入日记页面 6.进入收藏页面 7.注销账号 8.退出整个程序 >>> """ login_dic = { "username":None, "flag":False, "count":3 }
def wrapper(func): def inner(*args,**kwargs): if login_dic["flag"]: func() else: while login_dic["count"]: user = input("username:") pwd = input("password:") if user == "alex" and pwd == "alex123": login_dic["username"] = user login_dic["flag"] = True login_dic["count"] = 0 print("登录成功!") func() else: login_dic["count"] -= 1 print(f"用户名或密码错误!剩余次数{login_dic['count']}") return inner
def register(): pass
@wrapper def login(): pass
@wrapper def article(): print("这是文章")
@wrapper def comment(): print("这是评论")
@wrapper def log(): print("这是日记")
@wrapper def collect(): print("这是收藏")
@wrapper def out(): login_dic["username"] = None login_dic["flag"] = False print("退出成功!")
func_dic = { "1":login, "2":register, "3":article, "4":comment, "5":log, "6":collect, "7":out, "8":exit, }
while True: chose = input(msg) if chose in func_dic: login_dic["count"] = 3 if chose == "1": login() else: func_dic[chose]() else: print("请正确输入内容!")
|
装饰器版二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| msg = """ 1.请登录 2.请注册 3.进入文章页面 4.进入评论页面 5.进入日记页面 6.进入收藏页面 7.注销账号 8.退出整个程序 >>> """ login_dic = { "username":None, "flag":False, "count":3 }
def wrapper(func): def inner(*args,**kwargs): if login_dic["flag"]: func() else: login(func) return inner
def register(): pass
def login(func=False): while login_dic["count"]: user = input("username:") pwd = input("password:") if user == "alex" and pwd == "alex123": login_dic["username"] = user login_dic["flag"] = True login_dic["count"] = 0 print("登录成功!") if func: func() else: login_dic["count"] -= 1 print(f"用户名或密码错误!剩余次数{login_dic['count']}")
@wrapper def article(): print("这是文章")
@wrapper def comment(): print("这是评论")
@wrapper def log(): print("这是日记")
@wrapper def collect(): print("这是收藏")
@wrapper def out(): login_dic["username"] = None login_dic["flag"] = False print("退出成功!")
func_dic = { "1":login, "2":register, "3":article, "4":comment, "5":log, "6":collect, "7":out, "8":exit, }
while True: chose = input(msg) if chose in func_dic: login_dic["count"] = 3 func_dic[chose]() else: print("请正确输入内容!")
|
个人比较偏向第二种写法,因为这样就可以在装饰器中添加多个额外的功能,可读性还高