求助:实现可累计计数的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
相关产品推荐
相关产品推荐

