【问题标题】:What is the best way to combine various object and print them out accordingly?组合各种对象并相应打印出来的最佳方法是什么?
【发布时间】: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


    【解决方案1】:

    您正在引用上次在 while 循环中设置的局部变量 fname、lname 和 idNo。您需要的变量分别存储在 Student 类的每个实例中。试试这个 for 循环:

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

    【讨论】:

    • 谢谢你。不敢相信我错过了。
    • 别担心!很高兴我能帮上忙。
    猜你喜欢
    • 2020-11-26
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多