计数器变量为类

问题描述:

我有问题得到这段代码运行。这个班级是具有IdCounter的学生,这是问题出现的地方。 (在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的一部分。但我有已经越来越错误。

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

你看了下一行吗? – 2012-04-04 05:28:51

+0

为什么我没有想过...(原来我的代码写了'Student.idCounter = 0') – George 2012-04-04 05:32:58

+1

除了特定的错误,在Python中增量不是原子的,所以天真的计数器可能会导致竞争条件。更好的方法是使用'itertools.count'。 – bereal 2012-04-04 06:13:51

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) 

感谢Ignacio,Vazquez-Abrams指出的点点滴滴......

+0

也,请注意你的第一条评论是非常不准确的。 – 2012-04-04 05:32:54

+0

是的,实际上它只是一个柜台,没有别的。 (不知道怎么评论它,也许应该一起删除评论)。非常感谢Ignacio Vazquez-Abrams。 – George 2012-04-04 05:34:52