-4

I have to create a list of Student which contain name and roll number of student but when i am creating new object of class student ad appending it to my list every object in list are changed and getting same data for all student what should i do?? Code:

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: Output of code

Sergio
  • 324
  • 2
  • 12
Sohil Luhar
  • 3
  • 1
  • 5

1 Answers1

2

The syntax for the append method is as follow:

list.append(obj)

So you should replace students.append() by:

students.append(tmp)

Moreover, your print_info and input_info methods are not displaying the properties of a given student, but the properties of the class Student itself (which are always the same for every instance of the class). You should fix that.

Eldy
  • 1,027
  • 1
  • 13
  • 31