我在运行这段代码时遇到问题。该类是具有 IdCounter 的 Student,这似乎是问题所在。(第 8 行)
class Student:
idCounter = 0
def __init__(self):
self.gpa = 0
self.record = {}
# Each time I create a new student, the idCounter increment
idCounter += 1
self.name = 'Student {0}'.format(Student.idCounter)
classRoster = [] # List of students
for number in range(25):
newStudent = Student()
classRoster.append(newStudent)
print(newStudent.name)
我试图在我的Student
班级中使用这个 idCounter,所以我可以将它作为学生姓名的一部分(例如,这实际上是一个 ID# Student 12345
。但我一直出错。
Traceback (most recent call last):
File "/Users/yanwchan/Documents/test.py", line 13, in <module>
newStudent = Student()
File "/Users/yanwchan/Documents/test.py", line 8, in __init__
idCounter += 1
UnboundLocalError: local variable 'idCounter' referenced before assignment
我试图将 idCounter += 1 放在之前,之后,所有组合中,但我仍然收到referenced before assignment
错误,你能向我解释我做错了什么吗?