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

Python预算APP Category类实现及ledger金额求和问题求助

问题1解答

你看到的{"amount": 金额, "description": 描述}这种带键值对的{}结构是字典(dict),不是集合(Set)。
两者的核心区别是:

  • 字典存储的是键:值映射对,键必须唯一,写法是{key1: value1, key2: value2}
  • 集合存储的是无重复的独立元素,写法是{元素1, 元素2},没有冒号分隔的键值结构

问题2解答

要计算当前余额,只需要遍历ledger列表的所有字典元素,取出每个元素里amount字段的值累加即可。withdraw的实现逻辑如下:

  1. 先计算当前总余额
  2. 比较余额是否大于等于要提现的金额:
    • 足够:往ledger追加一条amount为负数的字典记录,返回True
    • 不足:直接返回False,不修改ledger

修正后的完整代码

class Category:
    def __init__(self, name):
        # 接收分类名称参数
        self.name = name
        self.ledger = []

    def deposit(self, amount, description=""):
        # description设置默认空字符串,不要用*description
        self.ledger.append({"amount": amount, "description": description})

    def get_balance(self):
        # 单独封装余额计算方法,复用更方便
        total = 0
        for item in self.ledger:
            total += item["amount"]
        return total

    def withdraw(self, amount, description=""):
        balance = self.get_balance()
        if balance >= amount:
            # 存入的金额是负数,键和deposit保持一致为amount
            self.ledger.append({"amount": -amount, "description": description})
            return True
        return False

原有代码的问题补充

  • __init__方法没有预留分类名称的入参,不符合实例化时传入分类名的要求
  • deposit方法的第二个参数用了*description可变参数,会把传入的描述转为元组,不符合要求,应该直接用description=""设置默认值
  • 原withdraw方法的逻辑完全不符合要求,存入的键用了withdrawal而非统一的amount,也没有做余额判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:09:02