我在运行这段代码时遇到问题。该类是具有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,因此我可以将其作为学生姓名的一部分(这实际上是一个ID#,例如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错误,您能向我解释我做错了吗?

最佳答案

必须通过类名称访问该类变量,在本示例中为Studend.idCounter:

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弄清楚了...

关于python - 类的计数器变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10005343/

10-11 19:37