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

求助:实现可累计计数的Counts类,当前代码调用报错

解决方案

你的核心问题是原代码的newvalue是实例方法,无法通过类直接调用,且没有用共享状态维护累计计数。以下是符合需求的实现:

class Counts:
    _current = 0  # 类变量,保存全局累计计数

    def __init__(self):
        self.value = self._current  # 实例初始化时同步当前类变量的值

    @classmethod
    def newvalue(cls, other):
        cls._current += other  # 更新全局累计值
        return cls()  # 返回新实例,用于输出当前累计值

    def __str__(self):
        return str(self.value)  # 定义实例被打印时的输出内容

功能验证

执行以下代码会得到你期望的结果:

print(Counts())          # 输出 0
print(Counts.newvalue(10))  # 输出 10
print(Counts.newvalue(40))  # 输出 50
print(Counts.newvalue(-17)) # 输出 33

关键说明

  • _current是类变量,所有Counts实例共享这个值,确保多次调用newvalue时能累计计数。
  • @classmethod装饰器让newvalue可以直接通过类(Counts.newvalue())调用,同时能修改类变量。
  • __str__方法定义了实例被打印时的输出内容,满足调用Counts()输出0的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:30:56