首页 > 解决方案 > Python OOP:为什么对象在打印中没有正确显示?

问题描述

我使用 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())

谁能告诉我我哪里出错了?提前致谢...

标签: pythonooppython-3.7

解决方案


这是解决方案:

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())

本质上,您打印的是学生对象而不是他们的姓名,并且通过一些列表理解,我们可以轻松修复它,同时还可以将其格式化以供输出。


推荐阅读