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

Python中Recurrent类__bool__方法返回值异常问题求助

问题解决方案

核心错误点

你在description方法里错误使用了bool(Recurrent),这是对Recurrent类本身做布尔判断,而Python中所有类对象的布尔值永远为True。正确做法是判断当前实例,即bool(self)。

额外优化建议

Recurrent作为Customer的子类,无需重复编写__init__方法的赋值逻辑,直接调用父类构造函数即可简化代码。

修正后的完整代码

prices_drink = {"milkshake": 5,"frappucino": 4, "water": 2,"coffee": 3, "soda": 3, "tea": 3}
prices_food = {"sandwich": 2, "cookie": 2, "pie": 3,"muffin": 3}

class Customer (object):
    def __init__(self, id, budget):
        self.id = id
        self.budget = budget

class Recurrent(Customer):
    def __init__(self, id, budget):
        # 调用父类构造函数,避免重复赋值
        super().__init__(id, budget)

    def __bool__(self):
        # 计算最贵饮品+最贵食物的总价
        max_total = max(prices_drink.values()) + max(prices_food.values())
        return self.budget > max_total  # 简化判断逻辑

    def description(self):
        # 用self代替Recurrent,判断当前实例的布尔值
        print(f"This is Customer {self.id}. They come here often. Can he buy? {bool(self)}")

customer2 = Recurrent(123456, 5)
customer2.description()

运行结果

执行后会输出:

This is Customer 123456. They come here often. Can he buy? False

符合预算5≤8的判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:50:25