8.9实验:汽车价值类实现报错求助——TypeError参数问题
错误原因排查
- 实例方法缺少
self参数:Python中类的实例方法必须以self作为第一个参数,调用实例方法时解释器会自动将当前实例对象传入该参数。你写的print_info()方法没有定义self参数,导致调用时传入实例对象后参数不匹配,触发TypeError。 - 属性类型错误:
purchase_price被初始化为空字符串'',不符合任务要求的int类型初始定义,应该初始化为整数0。 - 输出格式不符合要求:任务要求
print_info()的输出内容需用三个空格缩进,且第一行输出应为Car's information:,你的代码没有添加缩进,还多了不必要的换行。
正确代码实现
class Car: def __init__(self): self.model_year = 0 # 声明int类型的purchase_price属性 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方法,添加self参数,按要求格式化输出 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) 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()
内容的提问来源于stack exchange,提问作者Ash
相关产品推荐
相关产品推荐

