簡體   English   中英

如何在 python 腳本中定義“自我”

[英]How to define 'self' in python script

我只是在學習 python 中的類和方法,我有一個腳本,我不確定它為什么不起作用。 該腳本從控制台接受來自用戶的 integer,然后對於所需的學生帳戶數量,它會詢問用戶的名字、姓氏、年齡和用戶名。 然后應該打印學生列表和他們的默認密碼。 最后,它應該計算並打印輸入學生的平均年齡。 這是我的腳本。

#!/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 class。 defPassword()是一個實例方法,因此期望從實例調用,而您從 class 本身調用它。

您必須先創建 class CIT383Student的實例,然后才能對其調用defPassword() ,因為defPassword()不是 static 方法。

c = CIT383Student(first, last, age, username, current_password)
c.defPassword()
  • 在執行實例方法之前,您需要先實例化 class。
  • 不能像 class 方法那樣調用 defPassword 方法(實例方法)。
    student=CIT383Student(first,last,age,username,current_password)
    student.defPassword()
  • 您的代碼中還有另一個問題。 您錯過了定義 current_password 變量。 可能您需要添加此代碼。
current_password = input("Please enter current password")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM