为何Python代码会抛出'UnboundLocalError: local variable 'value' referenced'错误?
你的汽车折旧计算代码问题修复方案
先给你梳理下代码里的几个关键问题,再附上修正后的版本:
核心问题点
- 类方法里直接引用全局的
da_car实例,违背了类封装的设计原则,应该用self访问当前实例的属性 - 折旧逻辑错误:你写的是每年把价格乘0.15,这意味着每年只剩15%的价值,正常折旧应该是保留85%(即乘以
1 - 0.15) print_info方法依赖外部全局变量car_value,不符合类的设计规范,类的方法应尽量只依赖自身属性- 初始化实例后手动赋值属性,不如创建实例时直接传参数更简洁
- 存在拼写错误:
infortmation应为information
修正后的代码
class Car: def __init__(self, model=0, price=0, year=0): self.model = model self.price = price self.year = year # 初始化时直接计算当前价值,也可按需调用depreciate方法 self.current_value = self.depreciate() def depreciate(self): rate = 0.15 age = self.model - self.year current_price = self.price for _ in range(age): current_price *= (1 - rate) # 每年保留85%的价值,符合常规折旧逻辑 return round(current_price, 2) # 保留两位小数,符合货币展示习惯 def print_info(self): # 用f-string让输出更简洁易读 print(f"Car's information: \n Model year: {self.model} \n Purchase price: {self.price} \n Current value: {self.current_value}") # 先获取输入,再传入创建实例 model = int(input()) price = int(input()) year = int(input()) da_car = Car(model, price, year) da_car.print_info()
修正说明
- 所有方法改用
self访问实例属性,彻底摆脱对全局变量的依赖,符合类的封装原则 - 修正折旧计算逻辑,现在每年的价值是上一年的85%,这才是正常的折旧计算方式
- 把
current_value设为实例属性,print_info直接读取实例内部的值,无需依赖外部变量 - 创建实例时直接传入输入参数,代码结构更清晰
- 用f-string重构打印语句,比原拼接方式更简洁直观
- 给折旧结果保留两位小数,输出更贴合实际场景
内容的提问来源于stack exchange,提问作者Adam Ice
相关产品推荐
相关产品推荐

