Python面向对象编程:学生类和研究生类继承示例
以下是用Python定义的学生类(Student)和研究生类(GraduateStudent),并设计了主程序来展示继承特征:
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_student_id(self):
return self.student_id
def set_student_id(self, student_id):
self.student_id = student_id
def study(self):
print(f'{self.name} is studying.')
def sleep(self):
print(f'{self.name} is sleeping.')
class GraduateStudent(Student):
def __init__(self, name, student_id, research_area):
super().__init__(name, student_id)
self.research_area = research_area
def get_research_area(self):
return self.research_area
def set_research_area(self, research_area):
self.research_area = research_area
def research(self):
print(f'{self.name} is conducting research in {self.research_area}.')
def presentation(self):
print(f'{self.name} is preparing for a research presentation.')
student = Student('John', '12345')
print(student.get_name()) # 输出:John
print(student.get_student_id()) # 输出:12345
student.study() # 输出:John is studying.
grad_student = GraduateStudent('Alice', '67890', 'Computer Science')
print(grad_student.get_name()) # 输出:Alice
print(grad_student.get_student_id()) # 输出:67890
print(grad_student.get_research_area()) # 输出:Computer Science
grad_student.research() # 输出:Alice is conducting research in Computer Science.
grad_student.presentation() # 输出:Alice is preparing for a research presentation.
上述代码定义了一个学生类 Student,它有姓名(name)和学生ID(student_id)作为成员变量,还有学习(study)和睡觉(sleep)作为成员函数。然后定义了一个研究生类 GraduateStudent,它继承自学生类,并新增了研究领域(research_area)作为成员变量,以及研究(research)和学术报告(presentation)作为成员函数。
在主程序中,首先创建一个学生对象 student,并展示了访问成员变量和成员函数的特征。接着创建一个研究生对象 grad_student,也展示了访问继承的成员变量和成员函数的特征。
原文地址: https://www.cveoy.top/t/topic/vqE 著作权归作者所有。请勿转载和采集!