【发布时间】: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_row→self.one_row -
so...因为是同一个班,你还能用self吗?我的印象是它只在同一功能中使用。谢谢。
-
因为它在同一个instance中。我在下面发布了更完整的答案。
标签: python function class variables instance-variables