编写程序,创建基类Person,其成员包括两个实例属性name和age,实例方法 display ()用来输出实例属性的值;创建派生类Student,继承Person类,新增实例属性stuId(学号)和major(专业),并重写基类的display ()方法,输出Student类的实例属性的值。使用__init__()构造方法完成Person和Student类的对象初始化工作,并编写测试代码
时间: 2024-02-22 11:54:39 浏览: 117
可以的,下面是实现您要求的Python代码:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}\nAge: {self.age}")
class Student(Person):
def __init__(self, name, age, stuId, major):
super().__init__(name, age)
self.stuId = stuId
self.major = major
def display(self):
super().display()
print(f"Student ID: {self.stuId}\nMajor: {self.major}")
# 测试代码
person1 = Person("Tom", 30)
person1.display()
print("-----------------")
student1 = Student("Lucy", 20, "20210101", "Computer Science")
student1.display()
```
输出结果如下所示:
```
Name: Tom
Age: 30
-----------------
Name: Lucy
Age: 20
Student ID: 20210101
Major: Computer Science
```
阅读全文