用python 定义一个学生类,包括学号、姓名和出生日期3个属性;包含一个用于给属性初始化的构造函数;包含一个可计算学生年龄的方法。编写该类、生成2个实例
from datetime import datetime
class Student:
def __init__(self, sid:str, name:str, birthday:str) -> None:
self.studentId = sid
self.name = name
self.birthday = birthday
def getAge(self):
birthday = datetime.strptime(self.birthday, "%Y-%m-%d")
today = datetime.now()
age = ((today - birthday).days)//365
return age
def printInfo(self):
print(f"学号:{self.studentId}, 姓名:{self.name}, 年龄:{self.getAge()}")
stu1 = Student('20220001', '小明', '2002-10-25')
stu2 = Student('20220002', '小张', '1998-08-12')
stu1.printInfo()
stu2.printInfo()