Counter variable for class

George picture George · Apr 4, 2012 · Viewed 28.6k times · Source

I am having problem getting this piece of code to run. The class is Student which has a IdCounter, and it is where the problem seems to be. (at line 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)

I am trying to have this idCounter inside my Student class, so I can have it as part of the student's name (which is really an ID#, for example Student 12345. But I have been getting error.

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

I tried to put the idCounter += 1 in before, after, all combination, but I am still getting the referenced before assignment error, can you explain to me what I am doing wrong?

Answer

George picture George · Apr 4, 2012

The class variable has to be accessed via the class name, in this example Studend.idCounter:

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)

Thanks to the point out by Ignacio, Vazquez-Abrams, figured it out...