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

通过用户输入类名修改Python类属性报属性错误的解决方法咨询

错误原因与解决方法
  • 核心报错原因:你通过input()获取到的类选择结果是字符串类型,输入的Car/Motorcycle只是普通文本,和你提前定义的两个类没有关联,字符串对象本身没有color属性,所以调用class_x.color会抛出属性错误。
  • 解决思路:建立用户输入字符串与对应类对象的映射关系,拿到实际类对象后再修改属性即可。

修正后可运行代码

class Car:
    color = None
class Motorcycle:
    color = None

# 建立输入值和类的映射,后续新增类直接在此处添加即可
class_mapping = {
    "Car": Car,
    "Motorcycle": Motorcycle
}

class_input = input("Which class do you want to change the color of ? ")
color = input("What color do you want the class object to have ? ")

# 增加输入合法性校验,避免输入非法值报错
if class_input not in class_mapping:
    print("输入的类不存在,请输入 Car 或 Motorcycle")
else:
    target_class = class_mapping[class_input]
    
    def change_color(cls, input_color):
        cls.color = input_color
    
    change_color(target_class, color)
    print(target_class.color)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 22:45:02