定义一个Person类有name, age, sex的公有成员变量,以及一个showinfor()的方法对该类的三个属性进行打印。再定义一个Teacher类,该类继承Person类,并且额外新增一个department的公有成员变量,也对Teacher类定义一个showinfor()的方法对该类的四个属性进行打印。再定义一个Student类,该类继承Person类,并且额外新增一个marks的公有成员变量,也对Student类定义一个showinfor()的方法对该类的四个属性进行打印。 (2)完成上述题目的三个类的定义后,分别对不同的三个类创建一个实例对象并封装再一个列表里面,对该列表的三个不同对象按照年龄从从大到小进行排序,并打印排序后的结果。(建议使用lambda表达式对对象列表进行排序)。
时间: 2023-06-04 15:03:11 浏览: 96
JQuery扩展对象方法操作示例
好的,我明白了。以下是对你的问题的回答:
```
class Person:
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def showinfor(self):
print(f"Name: {self.name}, Age: {self.age}, Sex: {self.sex}")
class Teacher(Person):
def __init__(self, name, age, sex, department):
super().__init__(name, age, sex)
self.department = department
def showinfor(self):
print(f"Name: {self.name}, Age: {self.age}, Sex: {self.sex}, Department: {self.department}")
class Student(Person):
def __init__(self, name, age, sex, marks):
super().__init__(name, age, sex)
self.marks = marks
def showinfor(self):
print(f"Name: {self.name}, Age: {self.age}, Sex: {self.sex}, Marks: {self.marks}")
teacher1 = Teacher('Lucy', 32, 'Female', 'Math')
teacher2 = Teacher('Smith', 45, 'Male', 'Physics')
student1 = Student('John', 18, 'Male', 80)
student2 = Student('Alice', 20, 'Female', 92)
people_list = [teacher1, teacher2, student1, student2]
people_sorted = sorted(people_list, key=lambda p: p.age, reverse=True)
for p in people_sorted:
p.showinfor()
```
输出结果:
```
Name: Smith, Age: 45, Sex: Male, Department: Physics
Name: Lucy, Age: 32, Sex: Female, Department: Math
Name: Alice, Age: 20, Sex: Female, Marks: 92
Name: John, Age: 18, Sex: Male, Marks: 80
```
阅读全文