如何通过类内方法修改__init__中初始化的属性?实际问题求解
问题原因
你定义了calc_price方法来计算最终价格,但从来没调用过这个方法,所以final_price一直停留在__init__里初始化的0值。
解决方案
有几种可行的修复方式:
方式1:手动调用计算方法
创建实例后,显式调用calc_price再打印:
class Normal: def __init__(self,gp,g): self.gas_price = gp self.gallons = g self.final_price = 0 def calc_price(self): self.final_price = self.gas_price * self.gallons def __str__(self): return f"Normal gas price: {self.gas_price}. Gallons filled: {self.gallons}. Final price: {self.final_price}." c1 = Normal(4,15) c1.calc_price() # 必须先调用这个方法更新final_price print(c1)
输出结果:Normal gas price: 4. Gallons filled: 15. Final price: 60.
方式2:初始化时自动计算
如果希望实例创建后直接得到最终价格,把calc_price的调用放到__init__里:
class Normal: def __init__(self,gp,g): self.gas_price = gp self.gallons = g self.final_price = 0 self.calc_price() # 初始化时自动执行计算 def calc_price(self): self.final_price = self.gas_price * self.gallons def __str__(self): return f"Normal gas price: {self.gas_price}. Gallons filled: {self.gallons}. Final price: {self.final_price}." c1 = Normal(4,15) print(c1)
方式3:用@property实现动态计算(更优雅)
不需要维护final_price属性,每次访问时自动计算,避免忘记调用方法的问题,后续修改gas_price或gallons时,价格也会自动更新:
class Normal: def __init__(self,gp,g): self.gas_price = gp self.gallons = g @property def final_price(self): return self.gas_price * self.gallons def __str__(self): return f"Normal gas price: {self.gas_price}. Gallons filled: {self.gallons}. Final price: {self.final_price}." c1 = Normal(4,15) print(c1)
内容的提问来源于stack exchange,提问作者user21976909
相关产品推荐
相关产品推荐

