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

Python面向对象编程代码属性显示错误或顺序异常如何解决

Python面向对象代码问题排查与修复

问题根因

  • 你在changeThreat_level函数中错误创建了新的animal实例,赋值给原来的cat变量,直接覆盖了create()生成的存储了物种、年龄的旧实例,导致原有属性丢失。
  • 创建新animal实例时传参顺序和类__init__方法定义的参数顺序不匹配:__init__前两个参数是animal_species、age,你传入的是hunger_level、threat_level,所以属性赋值全部错位。

修复方案

修改逻辑为:直接在已创建的实例上修改属性,不新建实例覆盖原有数据,修改后的完整代码如下:

class animal():
    def __init__(self, animal_species="unknown", age=0, threat_level="peaceful", hunger_level=0): 
        self.animal_species = animal_species
        self.age = age
        self.hunger_level = hunger_level
        self.threat_level = threat_level

def create():
    animal_species = input("Enter species: ")
    age = int(input("Enter age: "))
    return animal(animal_species, age)

# 修改为接收已有的animal实例作为入参,直接修改实例属性
def changeThreat_level(animal_obj):
    hunger_level = int(input("Enter hunger(1-10): "))
    if hunger_level <= 3:
        threat_level = 'peaceful'
    elif 4 <= hunger_level <=7:
        threat_level = 'narky'
    else:
        threat_level = 'aggressive'
    # 直接修改原实例的属性,不用返回新实例
    animal_obj.hunger_level = hunger_level
    animal_obj.threat_level = threat_level


cat = create()
# 传入cat实例修改属性,不要重新赋值给cat覆盖原有实例
changeThreat_level(cat)

print("Animal's Attributes: ")
print("-------------------------")
print("The species of the animal is", cat.animal_species)
print("The age of the animal is", cat.age)
print("The animals threat level is", cat.threat_level)
print("The animals hunger out of 10 is around", cat.hunger_level)

验证说明

修改后会保留输入的物种、年龄信息,同时威胁等级、饥饿值也会按照输入的数值正常计算展示,不会出现属性丢失或顺序错误的问题。

内容的提问来源于stack exchange,提问作者Joss Glyn-Smith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:54:03