【发布时间】:2018-10-02 07:13:57
【问题描述】:
所以我正在尝试用 Python 编写一个程序来构建学生列表并最终将它们打印到屏幕上。对于用户选择添加的每个学生,都会输入名字、姓氏和身份证号。
我的问题是,虽然我试图将每个新创建的人附加到一个名为 studentList[] 的列表中,但当我在最后打印该列表时,我得到了正确数量的学生的输出,但都包含相同的作为我输入的最后一个学生的信息。
例如,如果我添加学生“Johnny Tsunami 4”、“Billy Bobblie 23”、“Biggus Dickus 77”,我的输出将显示为:
Biggus Dickus 77
Biggus Dickus 77
Biggus Dickus 77
我不确定我的错误在哪里,无论是在列表附加机制中还是在用于打印对象的 for 循环中。任何帮助是极大的赞赏。
class Student(object):
fname = ""
lname= ""
idNo = 0
def __init__(self, firstname, lastname, idnumber):
self.fname = firstname
self.lname = lastname
self.idNo = idnumber
def make_student(fname, lname, idNo):
student = Student(fname, lname, idNo)
return student
def main():
maxStudCount = 0
studentList = []
studQuery = raw_input("Would you like to add a student? (Type 'Yes' or 'No'): ")
while studQuery == 'Yes' and maxStudCount < 10:
fname = raw_input("Enter first name: ")
lname = raw_input("Enter last name: ")
idNo = raw_input("Enter ID No: ")
person = make_student(fname, lname, idNo)
studentList.append(person)
maxStudCount = maxStudCount + 1
studQuery = raw_input("Add another student? ('Yes' or 'No'): ")
for item in studentList:
print fname, lname, idNo
if __name__ =='__main__':
main()
【问题讨论】:
标签: python class for-loop append