设计- 一个学生类student和它的一个子类undergraduate. 要求如下:。 (1) Student 类有name和age属性,一个包含两个参数的构成方法,用于给name和age赋值,一个show方法打印student的信息+ (2)本科生类undergraduate增加一个degree属性,有一个包含三个参数的构造方法, 前两个参数用于给继承的name和age属性赋值,第三个参数给degree专业赋值,一个show方法用于打印undergraduate的属性信息 (3)在测试类中分别创建Student和undergraduate对象,调用他们的show方法。
时间: 2023-09-13 21:05:23 浏览: 226
可以按照以下代码实现:
```python
# 定义学生类
class Student:
# 构造方法
def __init__(self, name, age):
self.name = name
self.age = age
# 显示学生信息
def show(self):
print("姓名:{},年龄:{}".format(self.name, self.age))
# 定义本科生类,继承自学生类
class Undergraduate(Student):
# 构造方法
def __init__(self, name, age, degree):
# 调用父类构造方法
super().__init__(name, age)
self.degree = degree
# 显示本科生信息
def show(self):
# 调用父类show方法
super().show()
print("专业:{}".format(self.degree))
# 测试类
if __name__ == '__main__':
# 创建学生对象并显示信息
student = Student("张三", 20)
student.show()
# 创建本科生对象并显示信息
undergraduate = Undergraduate("李四", 22, "计算机科学与技术")
undergraduate.show()
```
输出结果为:
```
姓名:张三,年龄:20
姓名:李四,年龄:22
专业:计算机科学与技术
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)