定义一个学生类,其中有姓名、学号;有显示学生信息的show方法。在定义一个UndergraduateStudent类,它继承自Student类,新增加一个属性department,并重写show方法。
时间: 2024-05-14 13:19:37 浏览: 37
好的,您可以按照下面的代码实现您的需求:
```python
# 定义一个学生类
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
def show(self):
print('姓名:', self.name)
print('学号:', self.student_id)
# 定义一个本科生类,它继承自学生类
class UndergraduateStudent(Student):
def __init__(self, name, student_id, department):
super().__init__(name, student_id)
self.department = department
def show(self):
super().show()
print('专业:', self.department)
```
您可以通过下面的代码来测试这些类:
```python
# 创建学生对象并显示信息
student = Student('张三', '1001')
student.show()
print('------------------------')
# 创建本科生对象并显示信息
undergraduate_student = UndergraduateStudent('李四', '1002', '计算机科学与技术')
undergraduate_student.show()
```
输出结果应该为:
```
姓名: 张三
学号: 1001
------------------------
姓名: 李四
学号: 1002
专业: 计算机科学与技术
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)