gpt4 book ai didi

python - 类的计数器变量

转载 作者:IT老高 更新时间:2023-10-28 21:09:10 26 4
gpt4 key购买 nike

我在运行这段代码时遇到问题。该类是具有 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 类(class)中加入这个 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 放在 before、after、all 组合中,但我仍然收到 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com