繁体   English   中英

如何修复python中的“名称'self'未定义”错误?

[英]How to fix “name 'self' is not defined” error in python?

我正在尝试学习python OOP,但是我遇到了以下错误。

Exception has occurred: NameError
name 'self' is not defined
  File "/home/khalid/Desktop/MiniProject3/test1.py", line 27, in <module>
    login = first_class (self.Bank_Users.keys(), self.Bank_Users.values())
  File "/home/khalid/anaconda3/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/khalid/anaconda3/lib/python3.7/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/home/khalid/anaconda3/lib/python3.7/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)

我试图搜索可能已经解决的类似问题,但我找不到解决此错误的方法。

class first_class(object):

    def __init__(self, UserName, Password, Bank_Users):
        self.UserName = UserName
        self.Password = Password
        self.Bank_Users = {"Aldo": "1234"}


    def login_or_exit(self):

        while True:
            print("Please Enter User Name")
            self.UserName = input(">> ")
            print("Please Enter Password")
            self.Password = input(">> ")

            if self.UserName in self.Bank_Users.keys() and self.Password in self.Bank_Users.values():
                print("Logging into", self.UserName)

            else:
                print("Unsuccesful!!")

login = first_class (self.Bank_Users.keys(), self.Bank_Users.values())
login.login_or_exit()

正确执行此操作可能类似于:

class BankLoginSystem(object):
    def __init__(self, bank_users):
        self.bank_users = bank_users
        self.logged_in_user = None
    def login_or_exit(self):
        while True:
            print("Please Enter User Name")
            attempted_user = input(">> ")
            print("Please Enter Password")
            attempted_password = input(">> ")
            if attempted_password == self.bank_users.get(attempted_user):
                self.logged_in_user = attempted_user
                print("Success!!")
                return
            else:
                print("Unsuccesful!!")

# the user database is independent of the implementation
bank_users = { "Aldo": "1234" }

login = BankLoginSystem(bank_users)
login.login_or_exit()
print("Logged in user is: %s" % login.logged_in_user)

请注意,我们没有将用户名和密码作为对象的初始化参数-因为一个对象在其生命周期中可以有多个用户登录,所以这样做没有任何意义。

同样,应该保密的东西(例如尝试输入的密码)也不会存储在类成员变量中,而是严格保留为局部变量,这样它们就不会泄漏出去。 (在真实系统中,您希望您的密码数据库有盐渍的哈希值,而不是真实的密码,如果密码数据库本身泄漏,则包含损坏)。

顺便说一句,请注意,总的来说,将I / O逻辑与后端存储表示相结合是一个坏主意-通常,您希望让纯模型的对象独立于您的域,而与与用户进行的交互无关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM