如何将此文件读取函数转换为类



我有这个代码:

username = str(input("Enter Username: "))
password = str(input("Enter Password: "))
def search_username(file_path, username, password):
usernameTruthValue = False
passwordTruthValue = False
with open(file_path, 'r') as file:
# read all content of a file
content = file.read()
# check if string present in a file
if username in content:
usernameTruthValue = True
print("Username Valid")
else:
print("ERROR")
if password in content:
passwordTruthValue = True
print("Password Valid")
else:
print("ERROR")
if usernameTruthValue and passwordTruthValue == True:
print("Welcome")

search_username(r'/Users/name/PyCharmProjects/ADSProject/username.txt', username, password)

它应该检查文本文件中的字符串,并验证它们是否存在。它应该是用户名/登录系统的一个非常简化的版本。我真的很难把它变成一门课。我该怎么做?

谢谢

class Login():
def __init__(self, file_path, username, password):
self.file_path = file_path
self.username = username
self.password = password
def search_user_and_pass():
usernametruthvalue = False
passwordtruthvalue = False
with open(self.file_path, 'r') as file:
# read all content of a file
content = file.read()
# check if string present in a file
if self.username in content:
usernametruthvalue = True
else:
print("This username doesn't exist.")
if self.password in content:
passwordtruthvalue = True
else:
print("ERROR")
if usernametruthvalue == True and passwordtruthvalue == True:
print("yes")
#call next function here
Login('/Users/name/pythonProjects/ADS/user_pass.txt', "Molly", "1234")

当我输入错误的项目时,我预计会收到打印错误,但我什么也没收到。

在最核心的部分,您可能应该了解class方法的外观,特别是推断的自引用:

class Login():
def __init__(self, file_path, username, password):
self.file_path = file_path
self.username = username
self.password = password
def search_user_and_pass(self):
....

否则,类函数将不具有self的任何概念。还要验证所有间距是否正确,因为您复制的代码的间距不正确(类函数init和search_user_and_pass.的缩进相同

您也没有调用任何方法,Login将返回一个Class实例,但由于search_user_and_pass在init中没有被调用,因此该函数永远不会被调用。

my_login = Login('/Users/name/pythonProjects/ADS/user_pass.txt', "Molly", "1234")
my_login.seach_user_and_pass()

最新更新