【问题标题】:Python class giving error TracebackPython 类给出错误 Traceback
【发布时间】:2014-12-01 17:07:46
【问题描述】:

对不起,也许是一个愚蠢的问题,但我对 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'

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

【问题讨论】:

  • 您将 gpa 作为字符串传递 = 是否有理由这样做?
  • 它是一个数字,所以也可以通过 int 传递。见编辑
  • averageGPA 是一个函数,而不是一个字符串,所以你不能在其中添加studentGPA

标签: python class traceback


【解决方案1】:

您将 gpa 作为字符串传递:是否有理由这样做。如果你这样做会更好:

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

正如其他人所说,AverageGPA 是方法的名称,因此您需要为类属性取另一个名称。

另外,如果您使用 Python 2.7,您可能会发现您的平均值会出错

【讨论】:

  • 现在显示Traceback (most recent call last): File "Z:/CS 120/lab7_2.py", line 29, in &lt;module&gt; 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 += studentGPA TypeError: unsupported operand type(s) for +=: 'function' and 'int'
  • 好的,我做了一些更改,同时看到了新编辑的问题和错误\
  • 为什么 studentCount 一直在那里工作而不是平均 GPA...两者的定义方式相同
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 2015-05-25
  • 2013-05-15
  • 1970-01-01
  • 2021-08-05
  • 2020-08-09
  • 2014-12-25
  • 2013-12-04
相关资源
最近更新 更多