Python类给出错误Traceb

2024-04-23 23:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉问了一个愚蠢的问题,但我对python非常陌生,并创建了我的第一个类之一。但这是一个错误,我有点不知所措。这是密码

class Student:
    studentCount = 0
    averageGPA = 0

    def __init__(self, studentID, studentName, studentGPA):
        self.studentID = studentID
        self.studentName = studentName
        self.studentGPA = studentGPA
        Student.studentCount += 1
        Student.averageGPA += 3 

    def displayCount(self):
        print ("Total Students %d" % Student.studentCount)

    def displayStudent(self):
        print ("ID : ", self.studentID, ", Name : ", self.studentName, ", GPA : ", self.studentGPA)
    def averageGPA(self):
        print("Average GPA is : %d" % Student.averageGPA/Student.studentCount)

def main():
    student1 = Student("54466","Zara", 3)
    student2 = Student("48887","Manni", 4)
    student3 = Student("41187","Sam", 3)
    student1.displayStudent()
    student2.displayStudent()
    print ("Total Students %d" % Student.studentCount)
    print ("Student's average GPA %d" % Student.averageGPA)

main()

它给出的错误是

    Traceback (most recent call last):
  File "Z:/CS 120/lab7_2.py", line 29, in <module>
    main()
  File "Z:/CS 120/lab7_2.py", line 21, in main
    student1 = Student("54466","Zara", 3)
  File "Z:/CS 120/lab7_2.py", line 10, in __init__
    Student.averageGPA += 3
TypeError: unsupported operand type(s) for +=: 'function' and 'int'

请帮我解决这个问题。再次抱歉,如果这个问题听起来很愚蠢,因为我是新来的!!!你知道吗


Tags: selfmaindefcsstudentfileprintgpa
1条回答
网友
1楼 · 发布于 2024-04-23 23:33:09

你把gpa作为一个字符串传递:有理由这样做吗。如果你这样做会更好:

student1 = Student("54466","Zara", 3)

正如其他人所说,AverageGPA是一个方法的名称,因此您需要为class属性指定另一个名称。你知道吗

此外,如果您使用的是python2.7,您可能会发现您的平均值会出错

相关问题 更多 >