Counter variable for class
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 studentsfor number in range(25): newStudent = Student() classRoster.append(newStudent) print(newStudent.name)
Thanks to the point out by Ignacio, Vazquez-Abrams, figured it out...
Coming to this answer some time ago helped me find what I needed to sort out class versus instance variables and their scoping.So, an extension, which does the same thing, only using a generator. The generator assigns a unique number to the student as idCounter does -- only it consumes the values. There is no prev method on the generator class, of which I'm aware. Neither idGenerator nor idCounter is memoized, so if you want to externalize the list then come back to add one or more students, you'd have to update the range(start,,) accordingly, or iterate through each value without assigning it until you arrive at the unique one in sequence, a path somewhat shorter with idCounter which you cou simply set with a single dummy instance construct and go.
class Student: """ Implement a shared generator among all sub-classes in addition to idCounter. """ # A student ID counter idCounter = 0 # A student ID from generator idGenerator = (x for x in range(0xAAAAAA, 0xEEEEEE, 0xBA)) def __init__(self): self.gpa = 0 self.record = {} # Each time I create a new student, the idCounter increment Student.idCounter += 1 self.id = Student.idGenerator.__next__() self.name = f"{self.id} Student {Student.idCounter}"classRoster = [] # List of studentsfor number in range(25): newStudent = Student() classRoster.append(newStudent) print(newStudent.name)