我正在尝试创建一个登录系统。我可以在不实现类而仅实现函数的情况下制作系统。我想将每个步骤都变成特定的方法,而不必全部写入一个函数中。
我的问题是,如果字符长度> 5或密码错误,如何恢复为登录名,询问用户名和密码。
如果用户名和密码不在列表中,我该如何将其还原或需要再次编码?
class LoginSystem:
def __init__(self):
self.user_id = input("Please enter your user id: ")
self.user_password = input("Please enter your password: ")
def login(self):
username = self.user_id
password = self.user_password
if len(username) <= 5 and len(password) <= 5:
print("Logging In")
else:
print("Error! Max Length is 5 chars.") #return back to
login system
def check_system(self):
registered_user = {
"test@gmail.com": "test"
}
if self.user_id in registered_user:
print("Successful")
else:
new_user = input("Id not found! Are you are new user?\n [Y]es or [N]o\n")
new_user = new_user.lower()
if new_user == "Y":
return back to login system
elif new_user == "N": #how to return back to main login system
new_username = input("Please enter your user id: ")
new_userpassword = input("Please enter your password: ")
else:
return #back to login system
答案 0 :(得分:0)
您的LoginSystem
将错误的数据视为其实例属性。在各种方法调用之间,已注册用户的集合是不变的。 login
方法本身应提示输入用户ID和密码。
class LoginSystem:
def __init__(self):
self.users = {"test@gmail.com": "test"}
def login(self):
while True:
username = input("Please enter your user id: ")
password = input("Please enter your password: ")
if len(username) <= 5 and len(password) <= 5 and self.check_system(username, password):
print("Logging In")
break
else:
# TODO Disallow infinite retries to get it right
print("Error! Max Length is 5 chars.")
def check_system(self, name, password):
try:
expected_password = self.registered_user[name]
except KeyError:
# Or try to add a new user to the system here
return False
if password != expected_password:
return False
return True
可以添加一个单独的方法,以便在必要时向系统添加新用户。