python写出一个类People,并由该类做基类派生出子类Employee和Teacher。其中People类具有name、age两个成员变量,分别为String类型、整型,且具有公有的GetAge
时间: 2024-11-29 18:33:14 浏览: 18
好的,这是一个简单的Python例子,展示如何创建一个名为`People`的基类,以及两个从它派生的子类`Employee`和`Teacher`。在这个例子中,我们有共享的`name`和`age`属性,以及在基类中定义了获取年龄的方法`GetAge`:
```python
class People:
def __init__(self, name, age):
self.name = name
self.age = age
# 公共方法获取年龄
def GetAge(self):
return self.age
# 派生子类Employee
class Employee(People):
def __init__(self, name, age, job_title):
super().__init__(name, age)
self.job_title = job_title
# 派生子类Teacher
class Teacher(People):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject
# 示例
employee = Employee("张三", 30, "软件工程师")
teacher = Teacher("李四", 40, "数学老师")
print(employee.GetAge()) # 输出:30
print(teacher.GetAge()) # 输出:40
```
阅读全文