Zmienna licznika dla klasy
Mam problem z uruchomieniem tego fragmentu kodu. Klasą jest Student, który ma licznik IdCounter i tam właśnie pojawia się problem. (w linii 8)
<code>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) </code>
Próbuję mieć ten idCounter wewnątrz mojegoStudent
klasa, więc mogę mieć ją jako część imienia ucznia (na przykład jest to ID #Student 12345
. Ale dostawałem błąd.
<code>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 </code>
Próbowałem umieścić idCounter + = 1 przed, po, wszystkich kombinacjach, ale wciąż otrzymujęreferenced before assignment
błąd, możesz mi wyjaśnić, co robię źle?