Python中Product类的discount参数为何未按预期生效?
Product类折扣逻辑问题排查
你的代码与测试数据
Product类代码
class Product: discount_rate = 0.9 def __init__(self, name, cost, category, quantity, discount=False, profit_margin=0.1): self.name = name self.category = category self.discount = discount self.quantity = quantity if self.discount: self.actualCost = float(cost) * self.discount_rate if not self.discount: self.actualCost = float(cost) self.cost = self.actualCost + (self.actualCost * profit_margin)
测试数据
dummyData = [Product('name1', 100, 'misc', 4, True), Product('name2', 20, 'fruit', 2, False), Product('name3', 10, 'misc', 1, False), Product('name4', 5, 'misc', 10, True), Product('name5', 5, 'fruit', 3, True)]
问题原因分析
参数逻辑与预期不符
你说第一个实例预期actualCost=100、cost=110,但实际得到90和99,核心原因是你传入的discount=True,而代码逻辑中discount=True就是启用折扣:当discount为真时,actualCost会乘以0.9的折扣率,再在此基础上加10%利润,自然得到90和99。如果你的预期是该实例不启用折扣,应该传入discount=False。关于“无论True/False都生效折扣”的误解
你测试的第二个实例discount=False,按照代码逻辑,actualCost就是传入的20,cost是20*1.1=22,这是没有折扣的正常结果,和折扣生效的实例结果明显不同。你可能混淆了利润加成和折扣的概念,或者测试时误看了其他实例的数据。代码冗余优化建议
代码里判断discount用了两个独立的if,可以改成if-else结构,逻辑更清晰,避免冗余判断:
if self.discount: self.actualCost = float(cost) * self.discount_rate else: self.actualCost = float(cost)
修正方向
如果你实际需求是discount=True表示不启用折扣,discount=False才启用折扣,只需要把判断条件反转即可:
if not self.discount: self.actualCost = float(cost) * self.discount_rate else: self.actualCost = float(cost)
内容的提问来源于stack exchange,提问作者python newbie
相关产品推荐
相关产品推荐

