定义一个表示学生信息的Student类,封装类的属性 要求: (1)Student类的属性有:学号,姓名,python成绩,其中成绩、学号是私有变量 (2)Student类的方法有:封装成绩和学号的set,get的方法,输出信息 创建5个该类的对象,输出5个学生的信息,并输出5个学生的python平均分。
时间: 2024-03-25 08:38:23 浏览: 43
好的,以下是实现Student类的代码:
```python
class Student:
def __init__(self, student_id, name, python_score):
self.__student_id = student_id
self.__name = name
self.__python_score = python_score
def get_student_id(self):
return self.__student_id
def set_student_id(self, student_id):
self.__student_id = student_id
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def get_python_score(self):
return self.__python_score
def set_python_score(self, python_score):
self.__python_score = python_score
def output_info(self):
print("学号:{},姓名:{},python成绩:{}".format(self.__student_id, self.__name, self.__python_score))
```
接下来,创建5个Student对象并输出学生信息:
```python
students = []
students.append(Student("001", "张三", 90))
students.append(Student("002", "李四", 85))
students.append(Student("003", "王五", 77))
students.append(Student("004", "赵六", 92))
students.append(Student("005", "钱七", 88))
for student in students:
student.output_info()
```
输出结果如下:
```
学号:001,姓名:张三,python成绩:90
学号:002,姓名:李四,python成绩:85
学号:003,姓名:王五,python成绩:77
学号:004,姓名:赵六,python成绩:92
学号:005,姓名:钱七,python成绩:88
```
最后,计算并输出5个学生的python平均分:
```python
sum_score = 0
for student in students:
sum_score += student.get_python_score()
average_score = sum_score / len(students)
print("5个学生的python平均分为:{:.2f}".format(average_score))
```
输出结果如下:
```
5个学生的python平均分为:86.40
```
阅读全文