Ho riscontrato problemi nel far funzionare questo pezzo di codice. La classe è Student che ha un IdCounter, ed è qui che sembra essere il problema. (Alla linea 8)Variabile contatore per classe
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)
Sto cercando di avere questo idCounter dentro la mia classe Student
, così posso avere come parte del nome dello studente (che in realtà è un ID #, per esempio Student 12345
. Ma io ho state ottenendo l'errore.
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
ho cercato di mettere l'idCounter + = 1 in prima, dopo, tutte le combinazioni, ma sto ancora ottenendo l'errore referenced before assignment
, si può spiegare a me quello che sto facendo male?
Hai guardato la riga immediatamente successiva? –
Perché non ci ho pensato ... (In origine il mio codice ha scritto 'Student.idCounter = 0') – George
A parte l'errore particolare, gli incrementi non sono atomici in Python, quindi il contatore naive potrebbe causare condizioni di gara. Il modo migliore sarebbe usare 'itertools.count'. – bereal