对不起一个愚蠢的问题,但我对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'
请帮我解决这个问题。再次对不起,如果这个问题听起来很愚蠢,因为我很新!!!!/ / p>
答案 0 :(得分:0)
你将gpa作为字符串传递:是否有理由这样做。如果你这样做会更好:
student1 = Student("54466","Zara", 3)
正如其他人所说,AverageGPA是方法的名称,因此你需要另一个类属性的名称。
如果你使用Python 2.7
,你可能会发现你的平均值会出错