2012-04-04 16 views
10

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?

+1

Hai guardato la riga immediatamente successiva? –

+0

Perché non ci ho pensato ... (In origine il mio codice ha scritto 'Student.idCounter = 0') – George

+1

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

risposta

17
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) 

Grazie al commento di Ignacio, Vazquez-Abrams, l'ho capito ...

+0

, prendi nota che il tuo primo commento è grossolanamente impreciso. –

+0

Sì, in realtà è solo un contatore e nient'altro. (Non so davvero cosa commentare, forse dovrei semplicemente rimuovere il commento tutti insieme). Grazie infinite Ignacio Vazquez-Abrams. – George