将各种对象组合在一起并将其打印出来的最佳方法是什么?

时间:2018-04-21 22:37:24

标签: python class for-loop append

所以我试图用Python编写一个程序来构建一个学生列表,并最终将它们打印到屏幕上。对于用户选择添加的每个学生,将输入名字,姓氏和ID号。

我的问题是,虽然我试图将创建的每个新人追加到名为studentList []的列表中,但当我在最后打印列表时,我得到正确数量的学生的输出,但都包含相同的作为我输入的最后一名学生的信息。

例如,如果我添加学生&#39; Johnny Tsunami 4&#39; Billy Bobblie 23&#39; Biggus Dickus 77&#39;我的输出将为:< / p>

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()

1 个答案:

答案 0 :(得分:2)

您正在引用您最后在while循环中设置的局部变量fname,lname和idNo。您想要的变量分别存储在Student类的每个实例中。试试这个循环代替:

for item in studentList:
     print item.fname, item.lname, item.idNo