附加在功能中的列表不起作用

时间:2016-09-28 01:40:39

标签: python

这是我的班级:

from Student import Student
class Class:
    stulist=[]
    def __init__ (self, classname, numstudents):
        self.classname=classname
        self.numstudents=numstudents
    def addStudent(self, stuNum, stuName, stuGrades):
        Class.stulist.append(Student(stuName, stuGrades))
    def getPlace(self):
        print (Class.stulist[0].printLn()) #printLn is function in Student 
        print (Class.stulist[1].printLn())
        print (Class.stulist[2].printLn())

这是我的跑步者:

from Class import Class

class ClassRunner():
        def main():
            test=Class("Comp sci 1", 3)
            test.addStudent(0, "Jimmy","4 - 100 90 80 60")
            test.addStudent(1, "Sandy","4 - 100 100 80 70")
            test.addStudent(2,"Fred","4 - 50 50 70 68")
            test.getPlace()
        main()

我的输出显示:

Fred = 50 50 70 68

Fred = 50 50 70 68

Fred = 50 50 70 68

但我希望它显示:

Jimmy = 100 90 80 60

桑迪= 100 100 80 70

Fred = 50 50 70 68

我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:0)

Class班级self.stulist而不是Class.stulist

您正在修改类本身,而不是实例变量。

class Class:
    stulist=[]
    def __init__ (self, classname, numstudents):
        self.classname=classname
        self.numstudents=numstudents
    def addStudent(self, stuNum, stuName, stuGrades):
        self.stulist.append(Student(stuName, stuGrades))
    def getPlace(self):
        print (self.stulist[0].printLn()) #printLn is function in Student 
        print (self.stulist[1].printLn())
        print (self.stulist[2].printLn())

Class的引用将修改实际的Class对象本身。