我有一些非常基本的帐户登录系统的代码。问题是我的一个帐户有三个部分:uname
、upass
和 bal
。一切都工作正常,直到我引入 bal
。
我对 Python 非常业余,不知道如何修复它。我的意图是为我添加的每个帐户添加 3 个部分,即用户名、密码,然后是帐户余额,但到目前为止,我已经根据我的知识编写了尽可能合乎逻辑的代码,使其能够正常工作,但它似乎并不可行很好地打印或运行天平/bal
。
代码:
class Login:
def __init__(self):
self.users = {}
def addUser(self, uname, upass, bal):
self.users[uname] = upass, bal;
def login(self):
userNameInput = input("Username: ")
userPassInput = input("Password: ")
if userNameInput in self.users:
if userPassInput in self.users[userNameInput]:
print("Access Granted!")
self.access(userNameInput)
else:
print("Access Denied!")
return self.login()
def access(self, uname, bal):
print("Welcome, "+uname+"!"+bal)
def main():
mylogin = Login()
mylogin.addUser("u123", "p123", 123)
mylogin.login()
main()
错误:
Traceback (most recent call last):
File "C:\Users\Tom\Desktop\test.py", line 29, in <module>
main()
File "C:\Users\Tom\Desktop\test.py", line 27, in main
mylogin.login()
File "C:\Users\Tom\Desktop\test.py", line 14, in login
self.access(userNameInput)
TypeError: access() missing 1 required positional argument: 'bal'
额外的小问题:
对于“Def access”部分,由于某种原因,uname
的部分可以命名为任何名称,但在登录时仍会打印帐户的实际名称。对于我来说,为什么该部分完美地工作是没有意义的具有完全不同的名称。
最佳答案
问题在于 access
方法将 bal
作为参数,但在调用 时没有传递
。您只需在 bal
>self.access(userNameInput)access
方法中获取 bal
并删除 bal
参数即可。
此外,您不能在此处连接字符串和整数:print("Welcome, "+uname+"!"+bal)
。只需使用 str.format
即可。
class Login:
def __init__(self):
self.users = {}
def addUser(self, uname, upass, bal):
self.users[uname] = upass, bal
def login(self):
userNameInput = input("Username: ")
userPassInput = input("Password: ")
if userNameInput in self.users:
if userPassInput in self.users[userNameInput]:
print("Access Granted!")
self.access(userNameInput)
else:
print("Access Denied!")
# You shouldn't recurse here and use a loop instead.
# Python has a recursion limit.
return self.login()
# Remove the `bal` parameter.
def access(self, uname):
# Get the bal out of the self.users dict.
bal = self.users[uname][1]
print("Welcome, {}!{}".format(uname, bal))
def main():
mylogin = Login()
mylogin.addUser("u123", "p123", 123)
mylogin.login()
main()
关于Python-打印字典中的多个内容时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46109606/