如何在python脚本中定义“自我”

我只是在学习 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

对不起,如果这是一个太长的问题。我只是被难住了。任何帮助将不胜感激。

回答

在第 36 行,您调用

CIT383Student.defPassword()

您必须先实例化CIT383Student该类。defPassword()是一个实例方法,因此期望从实例调用,而您从类本身调用它。


以上是如何在python脚本中定义“自我”的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>