我正在学习python中的类和方法,我有一个脚本,我不知道为什么它不起作用。脚本从控制台接受用户的整数,然后根据所需的学生帐户数,询问用户的名字、姓氏、年龄和用户名。然后,它应该打印学生名单和他们的默认密码。最后,它应该计算并打印输入的学生的平均年龄。这是我的剧本
#!/usr/bin/python
def calcAverageAge(age_list):
average=sum(age_list) / len(age_list)
print("The average age of the students is:", average)
def validateAge():
while age < 15 or age > 45:
age=int(input("Age must be between 15 and 45"))
class CIT383Student: # class definition
def __init__(self,first,last,age,username,current_password):#contsructor
self.first_name=first # instantiate object create with first name, last name, age, username, and password
self.last_name=last
self.User_age=age
self.uname=username
self.pw=current_password
def defPassword(self): # Create default password for each user
import time #timestamp for default password
firstChar=self.first_name[0]
lastChar=self.last_name[0]
ts=time.time()
self.defPassword = (firstChar + lastChar + ts) # compute the default password for the user
#def displayUsers(self):
# print(self.first_name, self.last_name, self.User_age, self.uname, self.pw)
age_list = []
student_list =[]
studentNumber = int(input("Please Enter the number of student accounts: "))
for _ in range(studentNumber): #For each student
first = input("please enter the first name of the student: ")
last = input("Please enter the last name of the student: ")
age = input("please enter the age of the student")
username = input("Please enter username of the student")
CIT383Student.defPassword()
student=CIT383Student(first,last,age,username,current_password)
student_list.append(student)
for student in student_list:
CIT383Student.displayUsers()
print("\n")
calcAverageAge()
我收到的错误是:
Traceback (most recent call last):
File "filepath", line 36, in <module>
CIT383Student.defPassword(self)
NameError: name 'self' is not defined
如果这是一个太长的问题,很抱歉。我只是被难住了。任何帮助都将不胜感激
您必须先创建类
CIT383Student
的实例,然后才能对其调用defPassword()
,因为defPassword()
不是静态方法在第36行,你打电话
您必须首先实例化
CIT383Student
类defPassword()
是一个实例方法,因此需要从实例调用,而从类本身调用它相关问题 更多 >
编程相关推荐