Instanceof-使用类模拟系统访问

时间:2019-01-23 11:37:17

标签: python oop

我正在尝试使用类和方法来模拟系统访问门户。我希望能够使用input()向用户询问其用户名,检查该输入是否是User类的对象,如果是,请检查用户名的密码是否正确。当我使用它的实例返回false时。我该如何修改才能正常工作?

class User(): 

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def change_pw(self, new_password):
        self.password = new_password



jshannon = User("jshannon","AbC!23")
print(jshannon.username)
print(jshannon.password)

jshannon.change_pw("(i*u&y1")
print(jshannon.password)


input_user = input("What is your username? ")


print(isinstance(input_user, User))  

3 个答案:

答案 0 :(得分:3)

用户输入是字符串。总是。期。因此,您不能“检查该输入是否为User类的对象”-永远不会。

这里的解决方案是维护User实例的集合,并使用输入字符串搜索匹配的用户。

class UsersCollection(object):
    def __init__(self):
        # we store users in a dict, with user.usernale as key
        self._users = {}

    def add(self, user):
        if user.username in self._users:
            raise ValueError("username '{}' already in used".format(user.username))
        self._users[user.username] = user

    def get(self, username):
        return self._users.get(username)


users = UsersCollection()
users.add(User("jshannon","AbC!23"))

input_user = input("What is your username? ").strip()

userfound = users.get(input_user)
if userfound:
   # you can do something with your user
else:
   print("sorry, we don't know you")

请注意,这当然仅适合作为玩具项目。

答案 1 :(得分:1)

如果您使用的是Python 3.x(我将假设),则input返回一个字符串,因此isinstance(input_user, User)将始终为False

您将需要跟踪所有创建的User对象,并使用输入的名称搜索该对象。

有几种不同的方法可以做到这一点。我将假设用户名是唯一的,因此我将在共享集中使用它们:

class User:
    users = set()

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.users.add(username)

    def change_pw(self, new_password):
        self.password = new_password


jshannon = User("jshannon", "AbC!23")
print(jshannon.username)
print(jshannon.password)

jshannon.change_pw("(i*u&y1")
print(jshannon.password)

input_user = input("What is your username? ")

print(input_user in User.users)
# will output True if input_user is jshannon, otherwise False

请注意,这仅是示例,它也不是防弹的,也不是最佳设计(可能会争辩说users集是否甚至属于User提示:不是)。如果对象的用户名在初始化后更改,则该设置将不会更新,您可能会得到错误的结果。可以通过将self.username更改为属性来解决此特定问题,但我认为这超出了本问答的范围。

答案 2 :(得分:0)

我不确定这是否是您想要做的,但是您无法尝试 为您的班级list_of_usernames = []添加一个列表 然后在__init__()中将用户名附加到list_of_usernames并最后添加

print(input_user in User.list_of_usernames)

因此您的代码将如下所示

class User():
list_of_usernames = []
def __init__(self, username, password):
    self.username = username
    self.password = password
    self.list_of_usernames.append(username)
def change_pw(self, new_password):
    self.password = new_password



jshannon = User("jshannon","AbC!23")
print(jshannon.username)
print(jshannon.password)

jshannon.change_pw("(i*u&y1")
print(jshannon.password)


input_user = input("What is your username? ")


print(input_user in User.list_of_usernames)