如何在同一个 class 中引用第二个函数中的变量?

How to reference a variable in second function in the same class?

如何正确定义和调用这些函数?

我正在尝试构建一个将提示主菜单的应用程序,通过 logon 过程,转到下一个函数,即 login menu 并引用来自logon 功能使用户不必输入他们的 卡号和密码两次

我遇到的问题是试图能够在我的第二个函数中引用一个变量,它位于同一个 class 中。 我的同事告诉我使用全局变量是不好的,我不应该。这是代码。

我删除了一些不太重要的东西。例如,我想使用 elif choice ==3 语句来引用原始 one_row.

p.s。我已更改 def Login(self) 以包括我想引用的变量,但随后我的主菜单抱怨输入尚未定义。

class LoginPrompt:
    def Login(self):
        while True:
            print(menu[1])
            self.Card_number=str(input('>>  '))
            print(menu[2])
            self.Character_PINs = getpass.getpass('>>  ')
            self.one_row = c.execute('SELECT * FROM {tn} WHERE {cn}=? and {cnn}=?'.\
                            format(tn=table_1, cn=column_1, cnn=column_3),    (self.Character_PINs, self.Card_number,))
        for row in self.one_row.fetchone():
                print('Welcome: ', row)
                return

        else:
            print('PIN incorrect; try again')

    def loginMenu(self):
        while True:
            print(menu[5])
            print("\n1 - Deposit funds")
            print("2 - Withdraw funds")
            print("3 - Check balance")
            print("4 - Reset Pin")
            print("5 - Exit")

            while True:
                try:
                    choice = int(input("Please enter a number: "))
                except ValueError:
                    print("This is not a number")
                if choice >= 1 and choice <=5:
                    if choice == 1:
                        amount = input("\nPlease enter the deposit amount: ")
                        if amount != '' and amount.isdigit():
                            int(amount)
                            amount = c.execute('UPDATE {tn} SET Balances = ? WHERE {cn}=?'.\
                                                format(tn=table_1, cn=column_2), (amount,))
                        else:
                            print("Please enter a valid number")
                            conn.commit()
                            conn.close

                    elif choice ==3:
                        print(Login.one_row)

                    elif choice ==5:
                        input('Enjoy your stay, and always remember to drink Nuka Cola! ')
                        return(mainMenu)
                else:
                    return


def mainMenu():
        print(menu[0])
        chosen=False
        while not chosen:
        opt=int(input('\n Please choose one of the options below:\n\n-> Register for a new account [1]\n-> Login to an existing account [2]\n\nPlease type a number...\n\n>>  '))
        if opt==1:
            userReg()
            chosen=True
        elif opt==2:
            login_Menu = LoginPrompt()
            login_Menu.Login()
            chosen=True
            login_Menu.loginMenu()
        else:
            print('\n\nPLEASE TYPE EITHER 1 OR 2...\n ')
    print(chosen)
if __name__ == "__main__":
        while True:
            mainMenu()

在这里,您实例化了 LoginPrompt 的单个实例并在其上调用了 LoginloginMenu

login_Menu = LoginPrompt()
login_Menu.Login()
...
login_Menu.loginMenu()

因为你在Login中分配了一个实例变量self.one_row,你可以通过self.one_rowloginMenu中访问同一个实例变量:

class LoginPrompt:
    def Login(self):
        while True:
            ...
            self.one_row = ...
        ...

    def loginMenu(self):
        while True:
            ...

            while True:
                ...
                if choice >= 1 and choice <=5:
                    ...

                    elif choice == 3:
                        # print(Login.one_row)
                        print(self.one_row)

您可以在 Python 文档中阅读有关 self 和实例变量的更多信息:https://docs.python.org/3.8/tutorial/classes.html#class-and-instance-variables

关于代码风格的注意事项

在Python中,惯例是:

  • name 在 lower_case_with_underscores 中(和 CapWords 中的 classes)和
  • 在 class 名称后命名实例。
login_prompt = LoginPrompt()
login_prompt.login()
...
login_prompt.login_menu()

您可以在 Python 代码的 PEP 8 风格指南中阅读更多关于命名约定的信息:https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions