以下是一个用 Python 语言编写的实现上述功能的代码:

class Student:
    def __init__(self, student_id, name, score):
        self.student_id = student_id
        self.name = name
        self.score = score

class StudentGroup:
    def __init__(self):
        self.students = []

    def add_student(self, student):
        self.students.append(student)

    def get_average_score(self):
        total_score = 0
        for student in self.students:
            total_score += student.score
        if len(self.students) > 0:
            return total_score / len(self.students)
        else:
            return 0

# 测试代码
group = StudentGroup()

student1 = Student(1, 'Alice', 90)
student2 = Student(2, 'Bob', 85)
student3 = Student(3, 'Charlie', 95)

group.add_student(student1)
group.add_student(student2)
group.add_student(student3)

average_score = group.get_average_score()
print('平均成绩:', average_score)

这段代码定义了一个Student类,包含学生的学号、姓名和成绩。然后定义了一个StudentGroup类,用于管理学生对象。StudentGroup类中包含一个students列表,用于存储学生对象。通过add_student方法可以向students列表中添加学生对象。get_average_score方法用于计算学生的平均成绩,遍历students列表,累加所有学生的成绩,并除以学生人数得到平均成绩。

在测试代码中,创建了一个StudentGroup对象group,然后创建了三个学生对象,并使用add_student方法将它们添加到group对象中。最后调用get_average_score方法计算平均成绩,并打印输出结果。

Python 学生类实现:计算平均成绩

原文地址: https://www.cveoy.top/t/topic/f4nG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录