要求设计一个学生的类,包括学生的学号、姓名、年龄,还要有三项成绩:计算机成绩、数学成绩、英语成绩,要求可以求总分、平均分、最高和最低分,并且可以输出一个学生的完整信息
时间: 2024-09-27 19:14:26 浏览: 52
在Python中,你可以设计一个名为`Student`的类来满足这个需求。以下是该类的一个基本实现:
```python
class Student:
def __init__(self, id_number, name, age):
self.id_number = id_number
self.name = name
self.age = age
self.subject_scores = {
'计算机': None,
'数学': None,
'英语': None
}
def set_score(self, subject, score):
if score is not None and isinstance(score, (int, float)):
self.subject_scores[subject] = score
def get_total_score(self):
return sum(self.subject_scores.values()) if self.has_all_scores() else None
def get_average_score(self):
total = self.get_total_score()
if total is not None:
return total / len(self.subject_scores)
else:
return None
def get_highest_score(self):
return max(self.subject_scores.values()) if self.has_all_scores() else None
def get_lowest_score(self):
return min(self.subject_scores.values()) if self.has_all_scores() else None
def has_all_scores(self):
return all(score is not None for score in self.subject_scores.values())
def display_info(self):
scores = [f"{k}: {v}" for k, v in self.subject_scores.items() if v is not None]
total = self.get_total_score() or "无"
average = self.get_average_score() or "无"
highest = self.get_highest_score() or "无"
lowest = self.get_lowest_score() or "无"
print(f"学生ID: {self.id_number}, 姓名: {self.name}, 年龄: {self.age}")
print("成绩信息:")
for s in scores:
print(s)
print(f"总分: {total}, 平均分: {average}, 最高分: {highest}, 最低分: {lowest}")
# 示例用法
student = Student(1001, '小明', 18)
student.set_score('计算机', 90)
student.set_score('数学', 95)
student.set_score('英语', 85)
student.display_info()
```
在这个类中,我们定义了初始化方法`__init__`用于设置初始属性,以及一系列方法如`set_score`用于设置单科成绩,`get_total_score`、`get_average_score`、`get_highest_score` 和 `get_lowest_score` 来计算总分、平均分、最高分和最低分。`has_all_scores` 方法检查是否所有科目都有成绩,`display_info` 方法用于展示学生的完整信息。
阅读全文