【发布时间】:2019-06-16 03:55:52
【问题描述】:
我必须创建一个包含学生姓名和卷号的学生列表 但是当我创建班级学生广告的新对象时,将其附加到我的列表中,列表中的每个对象都会更改并为所有学生获取相同的数据 我该怎么办?? 代码:
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
【问题讨论】:
-
创建学生对象
-
Student.roll_no =和Student.name =没有按照你的想法去做。 -
@DeepSpace 那么如何打印这些值
-
请阅读重复的问题,了解类属性和实例属性的区别
-
您需要为此使用
__init__方法,并在那里初始化变量。