写一个类Animal, 包含成员变量name_animal和age_animal, 实例化age_animal, 并用sort函数将aga_animal排序,然后打印输出name_animal和age_animal
时间: 2023-11-26 20:06:43 浏览: 81
AGA-BP.zip_AGA matlab_BP 自适应_BP-AGA_自适应遗传 BP_自适应遗传bp
5星 · 资源好评率100%
以下是Animal类的实现:
```python
class Animal:
def __init__(self, name, age):
self.name_animal = name
self.age_animal = age
animals = [Animal("Dog", 5), Animal("Cat", 3), Animal("Rabbit", 2)]
# 使用sort函数将animals按年龄排序
animals.sort(key=lambda x: x.age_animal)
# 打印输出name_animal和age_animal
for animal in animals:
print("Name:", animal.name_animal, "Age:", animal.age_animal)
```
输出结果为:
```
Name: Rabbit Age: 2
Name: Cat Age: 3
Name: Dog Age: 5
```
阅读全文