简体   繁体   English

我在添加方法时遇到麻烦

[英]I'm having trouble making my add method

my code: 我的代码:

class Test(object):
    def __init__(self, number):
        self.number = number
    def __str__(self):
        return "This number is {}".format(self.number)
    def __add__(self, second):
        self.number = self.number + second.number
        return self
c1 = Test(1)
c2 = Test(2)
c2 = c1 + c2
print(c2)
print(c1)

Output: 输出:

This number is 3
This number is 3

my trouble is that it changes the c1 and c2, when I try to add them. 我的麻烦是,当我尝试添加它们时,它会更改c1和c2。 How do I keep c1 the same? 我如何保持c1不变?

Return a new object: 返回一个新对象:

class Test(object):
    def __init__(self, number):
        self.number = number

    def __str__(self):
        return "This number is {}".format(self.number)

    def __add__(self, second):
        return Test(self.number + second.number)

Note that when you rebind c2 like this: 请注意,当您像这样重新绑定c2时:

c2 = c1 + c2

its original value is lost. 它的原始值丢失了。 With your code, both c1 and c2 will point to the first Test object ( c1 + c2 returns self from c1 's __add__ ). 使用您的代码, c1c2都将指向第一个Test对象( c1 + c2c1__add__返回self )。

With my code, the original second object will be deleted and a new object will be bound to c2 . 使用我的代码,原始的第二个对象将被删除,新对象将绑定到c2

Your problem lies in the fact that you modify self in your __add__ method. 您的问题在于您在__add__方法中修改了self。 You're not supposed to do that (though you can, since Python considers all people involved to be "consenting adults"... and sometimes, it would be the correct solution. Though I can't think of a scenario where it would be) 您不应该这样做(尽管您可以这样做,因为Python认为所有参与的人都是“同意成年人”……有时,这将是正确的解决方案。尽管我无法想到一种解决方案是)

And self in your __add__ method gets bound to c1, so you modify c1; self__add__方法获取绑定到C1,所以你修改C1; and then you assign it to c2. 然后将其分配给c2。

Try adding print(c1 is c2) at the end. 尝试在最后添加print(c1 is c2) It will print True . 它将输出True

Pavel's __add__ behaves as an __add__ method is supposed to. Pavel的__add__行为与__add__方法的行为相同。

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

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