Python OOP:为什么打印时对象不能正确显示?

问题描述 投票:0回答:1

我使用VS代码运行下面的代码,这是输出。

图像: 注册学生的名字没有正确显示。

以下是我的代码。

# constructing multiple classes based on students with multiple courses

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

    def get_grade(self):
        return self.grade

class Course:
    def __init__(self, name, max_students):
        self.name = name
        self.max_students = max_students
        self.students = []   # blank list to add students to Course object

    def add_student(self, student):
        if len(self.students) < self.max_students:
            self.students.append(student)
            return True
        return False

    def get_average_grade(self):
        value = 0
        for student in self.students:
            value += student.get_grade()
        return value / len(self.students)

    def show_student(self):
        for i in self.students:
            return i


s1 = Student("Sha", 19, 95)
s2 = Student("Qam", 27, 97)
s3 = Student("Nemo", 2, 85)
s4 = Student("Lilo", 2, 99)
s5 = Student("Simba", 2, 87)

# add a course and specify max student
course1 = Course("Science", 2)  # 2 is the max course intake
course1.add_student(s1) # enrol student
course1.add_student(s2)

course2 = Course("Maths", 3)
course2.add_student(s3)
course2.add_student(s5)

# call the names of students in that course abd display the average grades of those students
print("The students enrolled in the", course1.name, "course are:", course1.show_student())
print("Average grade of students enrolled is:", course1.get_average_grade())

print("The students enrolled in the", course2.name, "course are:", course1.show_student())
print("Average grade of students enrolled is:", course2.get_average_grade())

谁能告诉我,我哪里出错了?先谢谢你了...

python oop python-3.7
1个回答
0
投票

这里是解决方案。

def show_student(self):
        return " ".join([student.name for student in self.students])
# and in this, you put course1.show_students() when it is course 2
print("The students enrolled in the", course2.name, "course are:", course2.show_student())

本质上,你打印的是学生对象,而不是他们的名字 通过一些列表的理解,我们可以很容易地解决这个问题,同时也可以形成输出。

© www.soinside.com 2019 - 2024. All rights reserved.