如何在python脚本中定义“self”

2024-10-03 06:25:11 发布

您现在位置: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

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


Tags: ofthenameselfforinputagedef
3条回答

您必须先创建类CIT383Student的实例,然后才能对其调用defPassword(),因为defPassword()不是静态方法

c = CIT383Student(first, last, age, username, current_password)
c.defPassword()

在第36行,你打电话

CIT383Student.defPassword()

您必须首先实例化CIT383StudentdefPassword()是一个实例方法,因此需要从实例调用,而从类本身调用它

  • 在执行实例方法之前,需要先实例化该类
  • 不能像类方法那样调用defPassword方法(实例方法)
    student=CIT383Student(first,last,age,username,current_password)
    student.defPassword()
  • 代码中还有一个问题。您没有定义当前密码变量。可能您需要添加此代码
current_password = input("Please enter current password")

相关问题 更多 >