从文件中读取用户名和密码与登陆状态并给要验证的函数加上装饰器
def get_username_and_pwd():
f = open("user_and_pwd","r+",encoding="utf-8")
user_pwd_state = f.read().split(",")
f.close()
return user_pwd_state
def change_state():
f = open("user_and_pwd","r+",encoding="utf-8")
f_new = open("user_and_pwd","r+",encoding="utf-8")
for line in f:
if "False" in line:
new = line.replace("False", "True ")
f_new.write(new)
continue
f_new.write(line)
f_new.close()
f.close()
def login(func):
#闭包
def inner():
if get_username_and_pwd()[2] == "False":
user = input("请输入你的用户名:")
pwd = input("请输入你的密码:")
if get_username_and_pwd()[0] == user and get_username_and_pwd()[1] == pwd:
print("您已经登陆成功...")
func()
change_state()
else:
print("用户名或者密码错误...")
elif get_username_and_pwd()[2].strip() == "True":
print("您已经成功登陆了,无需再输入用户名和密码")
func()
return inner
def home():
print("欢迎进入首页...")
@login
def China():
print("欢迎进入中国专区")
@login
def Usa():
print("欢迎进入Usa...")
home()
China()
Usa()
#下面是文件user_and_pwd里的内容(只有用户名,密码,登陆状态---<初始时是False>):
stary,123,False
====================================================================================
运行结果:
运行完之后,文件的登陆状态改为True

浙公网安备 33010602011771号