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

Python Car类报错:'Car'对象无'print_info'属性,求解决方案

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

错误根源

你犯了Python类定义的基础错误:把print_info方法写在了if __name__ == "__main__":代码块里,而非Car类的内部。类的所有方法必须定义在类的缩进范围内,否则Python不会将其识别为类的成员方法,Car实例自然找不到这个方法。你单独尝试的那段print_info代码也没有关联到Car类,同样会报错。

修正后的完整代码

class Car:
    def __init__(self):
        self.model_year = 0
        self.purchase_price = 0
        self.current_value = 0

    def calc_current_value(self, current_year):
        depreciation_rate = 0.15
        car_age = current_year - self.model_year
        self.current_value = round(self.purchase_price * (1 - depreciation_rate) ** car_age)
    
    # 将print_info方法放在Car类内部,与其他方法同级
    def print_info(self):
        print("Car's information:")
        print(" Model year:", self.model_year)
        print("Purchase price:", self.purchase_price)
        print("Current value:", self.current_value)  # 补充打印题目要求的current_value

if __name__ == "__main__":    
    year = int(input()) 
    price = int(input())
    current_year = int(input())
    
    my_car = Car()
    my_car.model_year = year
    my_car.purchase_price = price
    my_car.calc_current_value(current_year)
    my_car.print_info()

关键修改说明

  1. 方法位置调整:把print_info方法移到Car类内部,保持和__init__、calc_current_value相同的缩进级别,这样它才会成为Car类的成员方法。
  2. 补充缺失输出:按照题目要求添加了current_value的打印,确保输出所有指定属性。
  3. (可选优化)可以给__init__方法添加参数,直接初始化模型年份和购买价格,减少后续手动赋值步骤:
def __init__(self, model_year=0, purchase_price=0):
    self.model_year = model_year
    self.purchase_price = purchase_price
    self.current_value = 0

# 实例化时直接传参
my_car = Car(year, price)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:05:29