用python 定义一个学生类Student,包括实例属性姓名name,学号no;一个构造函数对实例属性初始化,和一个公有的实例方法show显示学生信息。再定义一个本科生UndergraduateStudent类,继承自Student类,新增加一个实例属性学院College和一个公有的实例方法show显示本科生的所有信息。
时间: 2024-03-01 09:49:38 浏览: 184
好的,这是Python定义一个学生类和本科生子类的代码实现:
```python
class Student:
def __init__(self, name, no):
self.name = name
self.no = no
def show(self):
print(f"姓名: {self.name}\n学号: {self.no}")
class UndergraduateStudent(Student):
def __init__(self, name, no, college):
super().__init__(name, no)
self.college = college
def show(self):
super().show()
print(f"学院: {self.college}")
```
在上面的代码中,首先定义了一个名为`Student`的类,它有两个实例属性`name`和`no`,分别表示学生的姓名和学号。然后在`__init__`构造函数中初始化了这两个实例属性。`show`方法用于显示学生信息,将姓名和学号输出到控制台上。
接下来,定义`UndergraduateStudent`本科生类,它继承自`Student`类。在`__init__`构造函数中,首先调用`super().__init__(name, no)`来初始化父类的实例属性。然后新增加了一个实例属性`college`,表示本科生所在的学院。`show`方法重载了父类的方法,先调用父类的`show`方法,然后输出本科生的学院信息。
现在我们可以创建一个学生对象和一个本科生对象,然后调用它们的`show`方法,看看输出的结果:
```python
s1 = Student("小明", "001")
s1.show()
s2 = UndergraduateStudent("小红", "002", "计算机科学与技术学院")
s2.show()
```
输出结果:
```
姓名: 小明
学号: 001
姓名: 小红
学号: 002
学院: 计算机科学与技术学院
```
阅读全文
相关推荐


















