使用接口和抽象函类进行写1.编写程序:在教学管理系统中有教师、教学管理人员和学生,定义一个抽象类 Person,用 Teacher、 Manager、 Student去继承 Person类,完成类的设计.
时间: 2024-02-06 13:11:45 浏览: 71
以下是使用接口和抽象类进行实现的程序:
```python
# 定义 Person 抽象类
from abc import ABC, abstractmethod
class Person(ABC):
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
@abstractmethod
def introduce(self):
pass
# 定义 Teacher 类,实现 IPerson 接口
class Teacher(Person):
def __init__(self, name, age, gender, department):
super().__init__(name, age, gender)
self.department = department
def introduce(self):
print(f"I am a teacher. My name is {self.name}, and I am {self.age} years old. I work in the {self.department} department.")
# 定义 Manager 类,实现 IPerson 接口
class Manager(Person):
def __init__(self, name, age, gender, title):
super().__init__(name, age, gender)
self.title = title
def introduce(self):
print(f"I am a manager. My name is {self.name}, and I am {self.age} years old. My title is {self.title}.")
# 定义 Student 类,实现 IPerson 接口
class Student(Person):
def __init__(self, name, age, gender, grade):
super().__init__(name, age, gender)
self.grade = grade
def introduce(self):
print(f"I am a student. My name is {self.name}, and I am {self.age} years old. I am in grade {self.grade}.")
```
在这个程序中,我们使用了一个抽象类 `Person`,其中定义了一个抽象方法 `introduce`。然后,我们分别定义了 `Teacher`、`Manager` 和 `Student` 三个类,它们都继承自 `Person` 类,并实现了 `introduce` 方法。这里我们没有用到接口,而是直接在类中实现了 `introduce` 方法。
我们可以使用这个程序,创建不同类型的人物对象:
```python
t = Teacher("Tom", 35, "male", "mathematics")
t.introduce() # 输出:I am a teacher. My name is Tom, and I am 35 years old. I work in the mathematics department.
m = Manager("Mary", 40, "female", "dean")
m.introduce() # 输出:I am a manager. My name is Mary, and I am 40 years old. My title is dean.
s = Student("Sam", 18, "male", 12)
s.introduce() # 输出:I am a student. My name is Sam, and I am 18 years old. I am in grade 12.
```
这样,我们就使用接口和抽象类完成了题目中要求的类的设计。
阅读全文