Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 类的计数器变量_Python_Class Variables - Fatal编程技术网

Python 类的计数器变量

Python 类的计数器变量,python,class-variables,Python,Class Variables,我在运行这段代码时遇到问题。这个班的学生有一个ID计数器,而问题似乎就在这里。(在第8行) 我试图在我的学生类中使用此ID计数器,以便将其作为学生姓名的一部分(这实际上是一个ID,例如学生12345),但我一直遇到错误 Traceback (most recent call last): File "/Users/yanwchan/Documents/test.py", line 13, in <module> newStudent = Student() File

我在运行这段代码时遇到问题。这个班的学生有一个ID计数器,而问题似乎就在这里。(在第8行)

我试图在我的
学生
类中使用此ID计数器,以便将其作为学生姓名的一部分(这实际上是一个ID,例如
学生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
回溯(最近一次呼叫最后一次):
文件“/Users/yanwchan/Documents/test.py”,第13行,在
newStudent=Student()
文件“/Users/yanwchan/Documents/test.py”,第8行,在__
idCounter+=1
UnboundLocalError:赋值前引用的局部变量“idCounter”

我试图在所有组合之前、之后输入idCounter+=1,但我仍然得到赋值前引用的
错误,你能解释一下我做错了什么吗?

必须通过类名访问类变量,在本例中
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找到了答案……

不久前的答案帮助我找到了分类类与实例变量及其范围所需的内容。 因此,一个扩展,它做同样的事情,只使用一个生成器。生成器给学生分配一个唯一的数字,就像idCounter一样——它只使用值。生成器类上没有prev方法,我知道这一点。idGenerator和idCounter都没有被记忆,所以如果你想外部化列表,那么c返回添加一个或多个学生时,您必须相应地更新范围(开始,,),或迭代每个值,而不分配它,直到您按顺序到达唯一的值,使用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)

你看了紧接着的那行了吗?为什么我没有想到…(我的代码最初写的是
Student.idCounter=0
)除了特定的错误之外,增量在Python中不是原子的,因此朴素的计数器可能会导致竞争条件。更好的方法是使用
itertools.count
。使用您的示例发布了问题的后续问题,请注意,您的第一个注释非常不准确。是的,实际上它只是一个计数器,什么也没有否则。(我真的不知道该怎么评论,也许应该把评论全部删除。)非常感谢伊格纳西奥·巴斯克斯·艾布拉姆斯。
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)