简体   繁体   English

没有得到预期的输出 - python 类

[英]not getting expected output- python classes

This is the output I am getting for the code given below: -4,-4这是 output 我得到的代码如下:-4,-4

The expected output: 8,-4预期output:8,-4

class arthemetic():
    def __init__(self,a):
        self.a=a
        self.b=a

    def __add__(self, other):
         self.a=self.b
         self.a+=other.a
         return self
    def __sub__(self, other):
        self.a = self.b
        self.a-=other.a
        return self
    def __str__(self):
        return str(self.a)


if __name__ =='__main__':
    a =arthemetic(2)
    b=arthemetic(6)
    print(*map(str,[a+b,a-b]))

You shouldn't mutate the object within your __add__ and __sub__ methods but return new objects instead.您不应该在__add____sub__方法中改变__add__ ,而是返回新对象。 By not doing that, the operations become non-deterministic.如果不这样做,操作就会变得不确定。 Both a + b and a - b return the a object after mutating it. a + ba - b都在变异后返回a对象。 That means that doing a - b actually changes the result from the previous a + b .这意味着执行a - b实际上会改变之前a + b的结果。 Since both reference the same object, you get the same result in both cases.由于两者都引用相同的 object,因此在两种情况下都会得到相同的结果。

-- from poke 's comment -- 来自poke评论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM