类的计数器变量

Geo*_*rge 17 python class-variables

我无法运行这段代码.该课程是学生,它有一个IdCounter,它就是问题所在.(第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)
Run Code Online (Sandbox Code Playgroud)

我想把这个idCounter放在我的Student班级里面,所以我可以将它作为学生名字的一部分(例如,它真的是一个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
Run Code Online (Sandbox Code Playgroud)

我尝试将idCounter + = 1放在之前,之后,所有组合中,但我仍然得到referenced before assignment错误,你能解释一下我做错了什么吗?

Geo*_*rge 31

class Student:
    # A student ID counter
    idCounter = 0
    def __init__(self):
        self.gpa = 0
        self.record = {}
        # Each time I create a new student, the idCounter increment
        Student.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)
Run Code Online (Sandbox Code Playgroud)

感谢伊格纳西奥的观点,巴斯克斯 - 艾布拉姆斯想出来......