如何在Python中定义一个具有姓名、工号和工资属性,以及work()方法的项目经理基类,然后创建两个子类继承该父类并重写或扩展必要的功能?
时间: 2024-11-20 10:40:06 浏览: 17
python中继承一个类共2页.pdf.zip
在Python中,你可以首先定义一个名为`ProjectManager`的基础类(Base Class),它包含姓名(name)、工号(employee_id)和工资(salary)属性,以及一个默认的行为(例如打印欢迎消息的`work()`方法)。然后创建两个子类,如`SoftwareManager`和`HardwareManager`,它们继承自`ProjectManager`并可能重写`work()`方法以体现特定领域的工作内容。
这是一个简单的例子:
```python
class ProjectManager:
def __init__(self, name, employee_id, salary):
self.name = name
self.employee_id = employee_id
self.salary = salary
def work(self):
print(f"{self.name} (ID: {self.employee_id}) is working on a project with a salary of ${self.salary}.")
# 创建子类并重写或扩展功能
class SoftwareManager(ProjectManager):
def work(self):
print(f"{self.name} (ID: {self.employee_id}) is working on software development projects.")
class HardwareManager(ProjectManager):
def work(self):
print(f"{self.name} (ID: {self.employee_id}) is managing hardware projects and ensuring smooth operations.")
# 实例化并使用
software_manager = SoftwareManager("张三", 1001, 8000)
software_manager.work() # 输出:张三 (ID: 1001) is working on software development projects.
hardware_manager = HardwareManager("李四", 1002, 9000)
hardware_manager.work() # 输出:李四 (ID: 1002) is managing hardware projects and ensuring smooth operations.
```
阅读全文