2012-04-04 8 views
10

このコードを実行する際に問題が発生しています。クラスはIdCounterを持つStudentクラスで、問題がどこにあるのかが分かります。 (8行目で)クラスのカウンタ変数

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) 

私は私のStudentクラス内でこのidCounterを持ってしようとしていますので、私はStudent 12345例えば、実際にID番号である学生の名前(の一部としてそれを持つことができます。しかし、私は持っています取得されたエラー。

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 

私はidCounterを入れてみました+ = 1の前に、後に、すべての組み合わせが、私はまだreferenced before assignmentエラーを取得しています、あなたは私が間違っているのものを私に説明できますか?

+1

すぐに次の行を見ましたか? –

+0

なぜ私はそれについて考えていないのですか(Orginally私のコードは 'Student.idCounter = 0'を書きました) – George

+1

特別なエラーの他に、インクリメントはPythonでは不可分ではないので、ナイーブなカウンタが競合条件を引き起こす可能性があります。より良い方法は 'itertools.count'を使うことです。 – bereal

答えて

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) 

Vazquez-Abramsのイグナシオの指摘のおかげで、...

+0

また、最初のコメントが大雑把に不正確であることに注意してください。 –

+0

さて、実際にはそれは単なるカウンターなのです。 (実際に何をコメントするか分からず、たぶんすべてのコメントを削除する必要があります)。 Ignacio Vazquez-Abramsさん、ありがとうございました。 – George