You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python OOP技术问询:如何自动更新类实例的age属性值?

解决方法

首先你代码里存在一个关键错误:最后一行person_with_highest_age = new_age_highest是将变量重新赋值为数字,而非修改实例的age属性,正确写法应为person_with_highest_age.age = new_age_highest。

核心结论:min()和max()返回的是列表中实例的引用,而非副本。因此当你修改person_with_lowest_age.age时,原实例(比如例子中的person2)的age会自动更新,完全不需要额外编写person2.age = person_with_lowest_age.age这类同步代码。

修正后的完整代码

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# 创建Person实例
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
person3 = Person("Charlie", 40)

people_list = [person1, person2, person3]

# 获取最小/最大年龄的实例(返回原对象引用)
person_with_lowest_age = min(people_list, key=lambda p: p.age)
person_with_highest_age = max(people_list, key=lambda p: p.age)

# 直接修改实例的age属性
person_with_lowest_age.age += 10
person_with_highest_age.age -= 10

# 验证:person2的age已自动更新为35
print(person2.age)  # 输出35

循环迭代中的自动更新逻辑

在while循环里,每次重新筛选当前最小/最大年龄的实例并修改属性即可,原实例的属性会自动同步:

# 示例循环逻辑,可根据需求替换终止条件
while True:
    # 每次重新获取当前列表中的最小/最大年龄实例
    lowest_person = min(people_list, key=lambda p: p.age)
    highest_person = max(people_list, key=lambda p: p.age)
    
    # 直接修改属性
    lowest_person.age += 10
    highest_person.age -= 10
    
    # 添加终止条件,比如当最小年龄超过某个值时退出
    if lowest_person.age >= 50:
        break

补充:封装年龄修改逻辑(可选)

如果想让代码更符合面向对象设计,可以给Person类添加专门的方法来修改年龄:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def increase_age(self, amount):
        self.age += amount
    
    def decrease_age(self, amount):
        self.age -= amount

# 使用时更直观
person_with_lowest_age.increase_age(10)
person_with_highest_age.decrease_age(10)

内容的提问来源于stack exchange,提问作者Peter Haidar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 08:13:11