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

Python类方法缩进错误致AttributeError:修复apply_discount属性缺失问题

问题解决:AttributeError: 'Item' object has no attribute 'apply_discount'

问题根源

你把calculate_total_price和apply_discount两个方法定义在了__init__方法内部,这会让它们变成__init__的局部函数,而非Item类的成员方法,因此类的实例无法访问这两个方法。

修改后的代码

class Item:
    pay_rate = 0.8  # 20%折扣后的支付比例

    def __init__(self, name: str, price: float, quantity=0):
        # 验证传入参数的合法性
        assert price >= 0, f"价格 {price} 不能小于0!"
        assert quantity >= 0, f"数量 {quantity} 不能小于0!"
        # 为实例属性赋值
        self.name = name
        self.price = price
        self.quantity = quantity

    def calculate_total_price(self):
        return self.price * self.quantity

    def apply_discount(self):
        self.price = self.price * Item.pay_rate

item1 = Item("Phone", 100, 1)
item1.apply_discount()
print(item1.price)  # 输出:80.0

额外优化建议

如果需要支持单个实例自定义折扣率,可以将apply_discount中的Item.pay_rate改为self.pay_rate,这样当某个实例修改了pay_rate属性时,会优先使用实例自身的折扣比例:

def apply_discount(self):
    self.price = self.price * self.pay_rate

示例用法:

item2 = Item("Laptop", 2000, 1)
item2.pay_rate = 0.7  # 给这个实例单独设置30%折扣
item2.apply_discount()
print(item2.price)  # 输出:1400.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:39:59