用Python定义一个学生类,包括学号,姓名,出生日期,bmi属性值,包含一个给属性值初始化的构造函数,包含一个可计算学生年龄的方法以及判断bmi等级的方法
时间: 2024-10-24 21:04:00 浏览: 45
在Python中,你可以定义一个名为`Student`的类,如下所示:
```python
class Student:
def __init__(self, student_id, name, birth_date, height, weight):
"""
构造函数,用于初始化学生的属性
"""
self.student_id = student_id
self.name = name
self.birth_date = birth_date
self.height = height # 米
self.weight = weight # 千克
self.bmi = self.calculate_bmi()
def calculate_age(self):
"""
计算学生年龄的方法
"""
from datetime import datetime
today = datetime.today()
age = today.year - self.birth_date.year
if today.month < self.birth_date.month or (today.month == self.birth_date.month and today.day < self.birth_date.day):
age -= 1
return age
def calculate_bmi(self):
"""
计算BMI指数的方法
"""
bmi = self.weight / (self.height ** 2)
return round(bmi, 2)
def bmi_status(self):
"""
判断BMI等级的方法
"""
bmi = self.bmi
if bmi < 18.5:
return "偏瘦"
elif 18.5 <= bmi < 24:
return "正常"
elif 24 <= bmi < 28:
return "超重"
else:
return "肥胖"
# 示例:
student1 = Student(1001, '张三', '1999-05-20', 1.75, 65)
print(f"学生{student1.name}的年龄是{student1.calculate_age()}岁")
print(f"BMI: {student1.bmi}, 等级: {student1.bmi_status()}")
```
阅读全文