编写程序,创建基类Person,其成员包括两个实例属性name和age,实例方法 display ()用来输出实例属性的值;创建派生类Student,继承Person类,新增实例属性stuId(学号)和major(专业),并重写基类的display ()方法,输出Student类的实例属性的值。使用__init__()构造方法完成Person和Student类的对象初始化工作,并编写测试代码。编写pythn完整代码,和步骤
时间: 2024-02-21 12:02:15 浏览: 69
步骤如下:
1. 定义基类Person,包括实例属性name和age,实例方法display()。
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age)
```
2. 定义派生类Student,继承Person类,新增实例属性stuId和major,重写基类的display()方法。
```python
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("Student ID:", self.stuId)
print("Major:", self.major)
```
3. 编写测试代码,分别创建Person和Student类的对象,并调用各自的方法进行测试。
```python
# 创建Person对象并测试
person = Person("John", 25)
person.display()
# 创建Student对象并测试
student = Student("Amy", 20, "20210001", "Computer Science")
student.display()
```
完整代码如下:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", 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("Student ID:", self.stuId)
print("Major:", self.major)
# 测试代码
# 创建Person对象并测试
person = Person("John", 25)
person.display()
# 创建Student对象并测试
student = Student("Amy", 20, "20210001", "Computer Science")
student.display()
```
阅读全文