class Student:
# 构造方法,用于初始化对象的属性
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
# 方法用于获取学生信息
def get_student_info(self):
return f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}"
# 方法用于学生学习
def study(self, subject):
return f"{self.name} is studying {subject}"
# 创建学生对象
student1 = Student("Alice", 18, "A")
student2 = Student("Bob", 17, "B")
# 调用对象的方法
info1 = student1.get_student_info()
study_result1 = student1.study("Math")
info2 = student2.get_student_info()
study_result2 = student2.study("History")
# 打印学生信息和学习结果
print(info1)
print(study_result1)
print(info2)
print(study_result2)
class HighSchoolStudent(Student):
# 新的构造方法,可以在其中初始化子类特有的属性
def __init__(self, name, age, grade, level):
# 调用父类的构造方法,初始化共享的属性
super().__init__(name, age, grade)
# 初始化子类特有的属性
self.level = level
# 新的方法,可以在子类中添加特有的行为
def participate_in_activity(self, activity):
return f"{self.name} is participating in {activity} as a high school student"
# 创建高中学生对象
high_school_student = HighSchoolStudent("Charlie", 16, "A", "Senior")
# 调用继承自父类的方法
info = high_school_student.get_student_info()
# 调用子类特有的方法
activity_result = high_school_student.participate_in_activity("Science Fair")
# 打印学生信息和活动参与结果
print(info)
print(activity_result)