1、 用一段完整的代码定义一个Person类,它包含数据成员age, name和gender。 # a.从Person中派生一个类Employee,在新类中添加一个数据成员,存储个人的number., # b、再从Employee中派生一个类Executive,每个派生类都应该定义一个方法,来显示相关的信息(名称和类型,如”Fred Smith is an Employee”)。 # c.编写一个列表,包含3个Executive对象,2个一般的Employee对象,然后显示它们的信息。
时间: 2024-02-20 22:58:41 浏览: 16
以下是完整的代码:
```python
class Person:
def __init__(self, age, name, gender):
self.age = age
self.name = name
self.gender = gender
class Employee(Person):
def __init__(self, age, name, gender, number):
super().__init__(age, name, gender)
self.number = number
def display_info(self):
print(f"{self.name} is an Employee")
class Executive(Employee):
def display_info(self):
print(f"{self.name} is an Executive")
exec1 = Executive(45, "John Doe", "Male", "E101")
exec2 = Executive(38, "Jane Smith", "Female", "E102")
exec3 = Executive(55, "Bob Johnson", "Male", "E103")
emp1 = Employee(28, "Samantha Brown", "Female", "E201")
emp2 = Employee(32, "Mike Smith", "Male", "E202")
employees = [exec1, exec2, exec3, emp1, emp2]
for emp in employees:
emp.display_info()
```
执行上述代码,将会输出以下信息:
```
John Doe is an Executive
Jane Smith is an Executive
Bob Johnson is an Executive
Samantha Brown is an Employee
Mike Smith is an Employee
```
注意:在上述代码中,Person类是Employee和Executive类的基类。Employee类包含一个新的数据成员number,并且覆盖了基类中的display_info()方法。Executive类也覆盖了display_info()方法。最后,我们创建了一个包含5个对象(3个Executive和2个Employee)的employees列表,然后遍历列表并调用每个对象的display_info()方法,以显示每个对象的信息。