【问题标题】:Create list of object in python [duplicate]在python中创建对象列表[重复]
【发布时间】: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__ 方法,并在那里初始化变量。

标签: python list class


【解决方案1】:

append方法的语法如下:

list.append(obj)

所以你应该将students.append()替换为:

students.append(tmp)

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

【讨论】:

  • 完成!但还是同样的问题
  • 是的,还有一些问题,我回答得有点快。我会尝试编辑我的答案以反映这一点。
  • 怎么做??
猜你喜欢
  • 2015-04-02
  • 1970-01-01
  • 2010-09-25
  • 2023-01-04
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多