类的计数器变量

时间:2012-04-04 05:22:47

标签: python class-variables

我无法运行这段代码。该课程是学生,它有一个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)

我正在尝试将这个idCounter放在我的Student课程中,所以我可以将它作为学生姓名的一部分(这实际上是一个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错误,你能解释一下我做错了什么吗?

2 个答案:

答案 0 :(得分:30)

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)

感谢伊格纳西奥的观点,巴斯克斯 - 艾布拉姆斯明白了......

答案 1 :(得分:1)

前一段时间来到这个答案,帮助我找到了整理类变量与实例变量及其作用域的方法。 因此,仅使用生成器即可完成相同功能的扩展。生成器会像idCounter一样为学生分配一个唯一的数字-只有它消耗这些值。我知道生成器类上没有上一个方法。 idGenerator和idCounter都不会被记忆,因此,如果您想外部化列表然后返回以添加一个或多个学生,则必须相应地更新范围(开始,,),或遍历每个值而不分配它,直到您依次到达唯一的一个,使用idCounter的路径要短一些,您只需用一个虚拟实例构造就可以设置路径并进行操作。

class Student:
    """ Implement a shared generator among all sub-classes
    in addition to idCounter. """

    # A student ID counter
    idCounter = 0
    # A student ID from generator
    idGenerator = (x for x in range(0xAAAAAA, 0xEEEEEE, 0xBA))

    def __init__(self):
        self.gpa = 0
        self.record = {}
        # Each time I create a new student, the idCounter increment
        Student.idCounter += 1
        self.id = Student.idGenerator.__next__()
        self.name = f"{self.id} Student {Student.idCounter}"

classRoster = [] # List of students
for number in range(25):
    newStudent = Student()
    classRoster.append(newStudent)
    print(newStudent.name)