python - 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())
谁能告诉我我哪里出错了?提前致谢...
解决方案
这是解决方案:
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())
本质上,您打印的是学生对象而不是他们的姓名,并且通过一些列表理解,我们可以轻松修复它,同时还可以将其格式化以供输出。
推荐阅读
- haskell - 删除单词的第一个字母并将其附加到末尾的函数(Haskell)
- java - JavaFX / Intellij 错误
- python - 在 Python 中过滤文件内容不起作用
- reactjs - 反应js | Jodit 编辑器表合并在生产构建后不起作用
- javascript - VueJS - 如何发送一个 JSON 数组的 POST 请求,每个数组除了每个数组元素的文件或图片之外,还包括数据
- python - 具有 3 个点的仿射变换和合并图像
- php - 从 MYSQL 数据创建数组以使用准备好的语句显示为复选框值
- regex - 正则表达式 - 在任何 m 字母窗口中匹配 n 次出现的子字符串
- python - 许多(最多 n 个或未知)字典的总和值
- javascript - 使用 Parcel bundler 生成 i18n 静态 HTML