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

Python类实例AttributeError:'Car'对象无'print_info'属性,请求排查

AttributeError: 'Car' object has no attribute 'print_info' 问题解决

错误原因

你调用的print_info()方法并未在Car类中定义,Python对象只能调用类中已声明的方法/属性,因此触发AttributeError。

解决步骤

1. 补充缺失的print_info方法

在Car类中添加用于打印车辆实例信息的print_info方法,修改后的完整类代码如下:

class Car:
    
    amount_cars = 0
    
    def __init__(self, manufacturer, model, hp):
        self.manufacturer = manufacturer
        self.model = model
        self.hp = hp
        Car.amount_cars += 1
    
    def print_car_amount(self):
        print("Amount: {}".format(Car.amount_cars))
    
    # 新增打印车辆信息的方法
    def print_info(self):
        print(f"厂商: {self.manufacturer}, 型号: {self.model}, 马力: {self.hp}")

2. 重新测试调用

执行以下代码:

myCar1 = Car("Tesla", "Model X", 525)
myCar1.print_info()

会输出预期结果:

厂商: Tesla, 型号: Model X, 马力: 525

额外说明

如果是方法名拼写错误(比如误将print_car_amount写成print_info),直接修正调用代码为myCar1.print_car_amount()即可,该方法会打印当前创建的车辆总数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:05:26