In Python, how do I check if an instance of my class exists?

泄露秘密 提交于 2020-01-05 17:13:12

问题


I'm making a program that asks the user to login, and I'm wondering how I can make it so it checks if an instance of my Username class exists. Oh and please excuse my sloppy and disorganized coding, I'm not very good at it.

quit_login = 1
class Usernames:
    def __init__(self, password):
        self.password = password
testlogin = Usernames("foo")
def login_e():
    a = raw_input("Please enter a username: ")
    new_pass = ""
    if isinstance(a, Usernames):
        a = Usernames(new_pass)
        print Usernames
    else:
        login_pass = raw_input("What is your password?\n")
        if login_pass == a.password:
            print "Hello", a
        else:
            print "Incorrect password"
while quit_login != 0:
    login_e()

回答1:


The missing piece is a collection to hold your Usernames instances. For this particular scenario, you probably want a dictionary.

>>> myDict = {}
>>> myDict['foo'] = 5
>>> 'foo' in myDict
True
>>> myDict['foo']
5
>>> myDict.get('bar', 'nope')
'nope'
>>> 


来源:https://stackoverflow.com/questions/6557349/in-python-how-do-i-check-if-an-instance-of-my-class-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!