[英]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__
). 使用您的代码,
c1
和c2
都将指向第一个Test
对象( c1 + c2
从c1
的__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.