如何使用Python类创建简单的登录命令行程序?

问题描述 投票:0回答:1

我正在尝试创建一个使用类来创建帐户的程序,然后允许用户登录帐户。它不以任何方式保证安全,仅供我学习。我想用参数名称,用户名和密码创建类的对象时遇到问题。我希望对象名称是用户在定义时输入的用户名。我遇到的问题是,当用户尝试登录该帐户时,它说用户输入的字符串与该类无关。我不确定这是否是由于登录功能或注册功能或两者所致。

class User:

    def __init__(self, name, username, password):
        self.name = name
        self.username = username
        self.password = password
        self.loggedIn = True


def home():
    print("Login, Register")
    a = input("What would you like to do: ")
    if(a == "register" or a == "Register"):
        register()
    elif(a == "Login" or a == "login"):
        login()
    else:
        print("Choose a valid option")
        home()
def register():
    n = input("Name: ")
    u = input("Username: ")
    p = input("Password: ")
    u = User(n, u, p)
    print("Welcome, " + u.name)
    home()
def login():
    l = input("Username: ")
    l2 = input("Password")
    if(l2 == l.password):
        print("Welcome, " + l.name)
    else:
        print("Incorrect username or password")
        login()
    home()

home()
python class command-line-interface
1个回答
0
投票

我想我有一件可以一劳永逸的东西。这里重要的是我们使用“ return”返回一个值,然后将该值携带到我们调用的下一个函数中。但是我认为,因为我们要在寄存器函数中创建u = User(n,u,p),因此它是一个局部变量,因此当您再次运行该函数时,它将用类的新实例和旧实例替换“ u”一则因为缺乏更好的语言而被替换。因此,换句话说,该类并没有得到真正的利用。我对此可能是错的。

class User:

    def __init__(self, name, username, password):
        self.name = name
        self.username = username
        self.password = password
        self.loggedIn = True


def home(registered, user):
    registered = False
    print("Login, Register")
    a = input("What would you like to do: ")
    if(a == "register" or a == "Register" and registered == False):
        register()
    elif(a == "Login" or a == "login" and registered == True):
        login(user)
    else:
        print("Choose a valid option")
        home()

def register():
        n = input("Name: ")
        u = input("Username: ")
        p = input("Password: ")
        u = User(n, u, p)
        print("Welcome, " + u.name)
        home(True, u)


def login(user):
    l = input("Username: ")
    l2 = input("Password")
    if(l2 == user.password):
        print("Welcome, " + user.name)
    else:
        print("Incorrect username or password")
        login(user)
    home(False, '')

home(False, '')
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.