我要做的是创建一个类,该类根据给定的单个参数进行计数,并自己进行算术运算。
class Counts:
def __init__(self, value=0):
self.value = value
def newvalue(self, other):
return Counts(self.value + other)
但是对于我对代码所做的每一次修改,我都会遇到任何不同的错误,无论是语法错误还是可调用参数。
思路是得到
Counts()
预期产出
0
下一个
Counts.newvalue(10)
预期产出
10
下一个
Counts.newvalue(40)
预期产出
50
下一个
Counts.newvalue(-17)
预期产出
33
等等
显示预期行为的代码是
class Counts:
value = 0
def __new__(self):
return self.value
@classmethod
def newvalue(cls, other):
cls.value += other
return cls.value
然而,这是一段有点奇怪的代码,因为您正在创建一个类,该类在初始化时返回一个值,而不是通过覆盖 __new__
从该类派生的对象,这是非常不标准的。
另外,如果您想在每次调用 Count()
时将值归零,您可以在 self.value = 0
return self.value
测试 ->
print(Counts())
print(Counts.newvalue(10))
print(Counts.newvalue(40))
print(Counts.newvalue(-17))
退货
0
10
50
33