2012-04-04 9 views
10

Mam problem z uruchomieniem tego kodu. Klasą jest Student, który ma IdCounter i tam właśnie pojawia się problem. (W linii 8)Zmienna licznika dla klasy

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) 

Staram się mieć ten idCounter wewnątrz mojego Student klasie, więc mogę mieć go jako część nazwy studenta (który jest naprawdę ID #, na przykład Student 12345. Ale mam dostaję błąd.

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 

próbowałem umieścić idCounter + = 1 w przed, po wszystkim kombinacja, ale ja wciąż uzyskiwanie błąd referenced before assignment można wytłumaczyć mi co robię źle?

+1

Czy spojrzałeś na linię natychmiast po? –

+0

Dlaczego nie pomyślałem o tym ... (Mój kod generalnie napisał 'Student.idCounter = 0') – George

+1

Oprócz określonego błędu, przyrosty nie są atomowe w Pythonie, więc naiwny licznik może powodować warunki wyścigu. Lepszym sposobem byłoby użycie 'itertools.count'. – bereal

Odpowiedz

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) 

Dzięki uwadze Ignacio, Vazquez-Abrams, wymyśliłem to ...

+0

Również , zauważ, że twój pierwszy komentarz jest rażąco niedokładny. –

+0

Tak, w rzeczywistości to tylko kontuar i nic więcej. (Nie bardzo wiem, co o tym mówić, może powinien po prostu usunąć komentarz razem). Bardzo dziękuję Ignacio Vazquez-Abrams. – George

Powiązane problemy