装饰器练习(任意页面如果未登录都需要登录)
# 获取文件内容 def open_text(login_text): with open(login_text, "r", encoding="UTF-8") as file: file = eval(file.read()) return file login_flag = False # 登录装饰器 def login_judge(file_text): def login_dl(f): def inner(): global login_flag if not login_flag: name_password = open_text(file_text) name = input("请输入账号:") password = input("请输入密码:") if name == name_password["name"] and password == name_password["password"]: print("登录成功!") login_flag = True f() else: print("账号密码错误") else: f() return inner return login_dl # 装饰器判断是否登录,页面内容展示 @login_judge("name_pw") def book(): print("book....") @login_judge("wx") def finance(): print("finance....") @login_judge("wx") def home(): print("home....") # 选择打开那个页面 list_index = ["book", "finance", "home"] while True: for index, i in enumerate(list_index): print(f"{index + 1}: {i}") input_number = input("请选择页面编号:") if input_number == "1": book() elif input_number == "2": finance() elif input_number == "3": home()