Python:使用其他类的类

时间:2015-04-23 17:19:31

标签: python python-2.7

所以我有2个文件可以使用彼此的类一起工作。

我有

class Student:
    """A class to model a student with name, id and list of test grades"""
    def __init__(self, name, id):
        """initializes the name and id number; sets list of grades to []"""
        self.s_name = name
        self.ident = id
        self.tests=[]

    def getID(self):
        return self.ident

    def get_name(self):
        """ returns the student name"""
        return self.s_name
    def addtest(self,t):
        """adds a grade to the list of test grades """
        self.tests.append(t)
    def __str__(self):
        """returns the student name and the current list of grades"""
        return self.s_name + "  " + str(self.tests) + "  " 

    def comp_av(self):
        """returns the average of the current set of grades or 'no grades'
        if appropriate"""
        if len(self.tests) > 0:
            sum = 0.0
            for item in self.tests:
                sum = sum + item
            average = float(sum)/len(self.tests)
            return average
        else:
            return "no grades"

完全完成了。我也有从教师的角度来看的代码。学生不仅仅是由他们的名字代表,而是由班级Student的对象代表。每个Student对象都有自己的名称和ID号,但也有一个测试分数列表。现在课程只有构造函数和__str__方法。

from LabStudentClass import *

class Course:
    """ A class to model a course which contains a list of students"""
    def __init__(self,teacher):
        """Sets up a class to hold and update students"""
        self.students = []
        self.teacher = teacher

    def __str__(self):
        """ prints the course by listing each student in the class"""
        result = self.teacher+"'s Class\n"
        for s in self.students:
            name = s.get_name()
            result = result + name + '\n'

        return result

c = Course("Dr. Bradshaw")
#print c

def AddStudent(name, id):
    student1 = Student('Mary Comtpon', '3456')
    student2 = Student('Billy Jo', '2345')
    student3 = Student( 'Anne lou', '1090')

    print student1
    print student2
    print student3

我的目标是创建方法AddStudent:此方法获取两个参数,即学生姓名和ID。创建一个新的Student对象并将其添加到课程中。

在课堂上添加3名学生并打印出课程进行测试。

但是,学生不打印,我不确定问题是什么。

1 个答案:

答案 0 :(得分:0)

将此方法添加到Course班级:

def addStudent(self, name, id):
    student = new Student(name, id)
    self.students.append(student)

然后,使用以下内容替换您在底部编写的功能:

c.addStudent('Mary Comtpon', '3456')
c.addStudent('Billy Jo', '2345')
c.addStudent('Anne lou', '1090')

print c