类的项目总和

huangapple go评论73阅读模式
英文:

Sum of items of a class

问题

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

依此类推。

英文:

What I have to do is to create a class that counts from a giving single argument and itself make the arithmetical operation.

class Counts:
    def __init__(self, value=0):
        self.value = value
        
    def newvalue(self, other):
        return Counts(self.value + other)

But for every I make to the code I got any different error, either syntax or callable argument.

The idea is to get

Counts()

Expected output

0

Next

Counts.newvalue(10)

Expected output

10

Next

Counts.newvalue(40)

Expected output

50

Next

Counts.newvalue(-17)

Expected output

33

And so on.

答案1

得分: 2

代码显示预期行为的部分是

class Counts:
    value = 0
    def __new__(self):
        return self.value

    @classmethod
    def newvalue(cls, other):
        cls.value += other
        return cls.value

然而,这是一个有点奇怪的代码片段,因为它创建了一个类,该类在初始化时返回一个值,而不是通过覆盖 __new__ 从该类派生的对象,这在相当不标准。

另外,如果你想在每次调用 Count() 时将值归零,你可以在 return self.value 之前添加 self.value = 0

测试结果如下:

print(Counts())
print(Counts.newvalue(10))
print(Counts.newvalue(40))
print(Counts.newvalue(-17))

返回结果如下:

0
10
50
33
英文:

The code that shows the expected behaviour is

class Counts:
    value = 0
    def __new__(self):
        return self.value
    
    @classmethod
    def newvalue(cls, other):
        cls.value += other
        return cls.value

however this is a somewhat strange piece of code, as you are creating a class that returns a value when initialized instead of an object deriving from that class by overriding __new__, which is pretty non-standard.

also if you want to zero the value whenever Count() is called, you can add a self.value = 0 before the return self.value

Tests ->

print(Counts())
print(Counts.newvalue(10))
print(Counts.newvalue(40))
print(Counts.newvalue(-17))

returns

0
10
50
33

huangapple
  • 本文由 发表于 2023年2月19日 05:17:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496447.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定