定义一个名为student的类,完成sid、name、age的赋值并定义类方法avg_age计算全部学生的平均年龄
时间: 2023-07-10 21:06:40 浏览: 40
以下是一个可能的实现:
```python
class Student:
students = []
def __init__(self, sid, name, age):
self.sid = sid
self.name = name
self.age = age
self.students.append(self)
@classmethod
def avg_age(cls):
total_age = sum([s.age for s in cls.students])
return total_age / len(cls.students)
```
这个类有三个属性:学生的学号(sid)、姓名(name)和年龄(age),以及一个类变量 `students`,用于存储所有创建的学生对象。
构造函数 `__init__` 接受三个参数,并将它们分别赋值给实例变量 `sid`、`name` 和 `age`。然后将新创建的学生对象添加到 `students` 列表中。
类方法 `avg_age` 计算所有学生的平均年龄。它首先计算所有学生年龄的总和,然后除以学生人数,得到平均年龄。
使用示例:
```python
s1 = Student('001', 'Alice', 20)
s2 = Student('002', 'Bob', 21)
s3 = Student('003', 'Charlie', 19)
print(Student.avg_age()) # 输出 20.0
```
这里创建了三个学生对象,并调用了类方法 `avg_age` 计算平均年龄。由于学生的年龄分别为 20、21 和 19,所以平均年龄为 20.0。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)