在python

时间:2019-01-22 16:16:58

标签: python list class

我必须创建一个学生列表,其中包含学生的姓名和编号 但是当我创建班级学生广告的新对象时,将其添加到我的列表中,列表中的每个对象都会更改,并且所有学生的数据都相同 我该怎么办?? 代码:

class Student:
    name = 'abc'
    roll_no = 1

    def print_info (self):
        print(Student.name,"\t",Student.roll_no)

    def input_info (self):
        Student.roll_no = int(input("Enter Student roll number  "))
        Student.name = input("Enter Student name  ")

ch=1
students = []

while ch!=3:
    print("1.Create new Student\n2. Display students\n3.Exit")
    ch=int(input("Enter choice\t"))`enter code here`
    if ch==1 :
        tmp=Student()
        tmp.input_info()
        students.append(tmp)
    elif ch==2:
        print("---Students Details---")
        print("Name\tRoll No")
    for i in students:
        i.print_info()

输出: Output of code

1 个答案:

答案 0 :(得分:1)

append方法的语法如下:

list.append(obj)

因此,您应将students.append()替换为:

students.append(tmp)

此外,您的print_infoinput_info方法不会显示给定学生的属性,而是显示类Student本身的属性(对于每个实例的属性总是相同的班级)。你应该解决这个问题。