我刚开始使用课程,我决定创建一个快速登录程序。 该程序应该设置一个用户并让他们登录但我每次运行程序时都会收到一个NameError我检查了拼写,一切似乎都是正确的。任何帮助将不胜感激
class User(object):
def __init__(self, name1, name2 , age , username, passw):
self.name1 = name1
self.name2 = name2
self.age = age
self.username = username
self.passw = passw
def user_setup(self):
try:
name1 = str(input("Please enter your first name : "))
try:
name2 = str(input("Please enter your last name : "))
try:
age = int(input("Please enter your age in years"))
except ValueError:
print("Thats not allowed")
except ValueError:
print("Thats not allowed")
except ValueError:
print("Thats not allowed")
self.username = self.name1[0:3] + str(self.age)
return self.username
def login(self):
for i in range(4):
loginUsername = input("Please enter your username : ")
if loginUsername == self.username:
loginPassword = input("Please enter your password : ")
if loginPassword == self.passw:
print("You have loggged in as " + self.username)
else:
print("invalid")
else:
print("invalid")
print("You have entered your username or password incorrectly too many times")
quit()
def main():
menu = int(input("1.new user\n2.login\n-"))
if menu == 1:
user_setup()
login()
elif menu == 2:
login()
print("test")
main()
我运行程序时遇到的错误:
1.new user
2.login
-1
Traceback (most recent call last):
File "C:\Users\colin\Desktop\Python programs\Password generator.py", line 58, in <module>
main()
File "C:\Users\colin\Desktop\Python programs\Password generator.py", line 50, in main
user_setup()
NameError: name 'user_setup' is not defined
答案 0 :(得分:0)
将user_setup()
更改为User.user_setup()
中的main()
,因为user_setup()
是User
类的方法,python不会将其视为普通函数
您还希望将login()
更改为User.login()
但是,类以其他方式使用,例如,通常通过组合user_setup()
和__init__()
然后以这种方式创建用户来创建新用户:
user1 = User(...)
答案 1 :(得分:0)
user_setup
是该类的一个方法,因此您需要先将其实例化,然后才能使用它:
user = User(name1='foo', name2='bar', age=21, username='foobar', password='secret')
user.user_setup()
答案 2 :(得分:0)
SELECT TO_CHAR( year, 'yyyy' ) AS year,
TO_CHAR( day_month, 'dd-mm' ) AS day_month
FROM your_table;
是user_setup()
的一种方法。您需要创建一个User
实例,然后像这样调用方法
User
如果您想先调用它而不先实例化,请将user = User(name1, name2, age, username, passw)
user.user_setup()
设为classmethod并使用如下:
user_setup
答案 3 :(得分:0)
您需要创建一个User实例,然后调用适当的方法。此外,在__init__
中,您需要为参数名称等提供默认值。