【问题标题】:How to reference a variable in second function in the same class?如何在同一类的第二个函数中引用变量?
【发布时间】:2020-04-05 20:24:00
【问题描述】:

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

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

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

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

附言我已更改 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()

【问题讨论】:

  • Login.one_rowself.one_row
  • so...因为是同一个班,你还能用self吗?我的印象是它只在同一功能中使用。谢谢。
  • 因为它在同一个instance中。我在下面发布了更完整的答案。

标签: python function class variables instance-variables


【解决方案1】:

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

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

由于您在Login 中分配了实例变量self.one_row,因此您可以通过loginMenu 中的self.one_row 访问相同的实例变量:

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 中,约定是:

  • lower_case_with_underscores(以及CapWords中的类)中一致地命名函数,并且
  • 在类名之后命名实例。
login_prompt = LoginPrompt()
login_prompt.login()
...
login_prompt.login_menu()

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

【讨论】:

  • 在您的实际代码中def loginMenu(self): 是否缩进在class LoginPrompt: 下?
  • 是的。抱歉,网站让我重新缩进所有内容。
  • 您可以使用代码围栏来避免重新缩进:stackoverflow.com/editing-help#code
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
相关资源
最近更新 更多