class a:
def __init__(self,val):
self.val=val
def __add__(self,other):
if isinstance(other,a):
print("other 变量变化前 other=",other) #语句 1
other=other.val
print("other 变量变化后 other=",other) #语句 2
return a(self.val+other)
x=a(8)
y=a(9)
print("x+y 之前 y=",y) #语句 3
print("x+y=",x+y)
print("x+y 之后 y=",y) #语句 4
上面代码的输出如下:
x+y 之前 y= <__main__.a object at 0x01F16270>
other 变量变化前 other= <__main__.a object at 0x01F16270>
other 变量变化后 other= 9
x+y= <__main__.a object at 0x01F16290>
x+y 之后 y= <__main__.a object at 0x01F16270>
我的问题是:
1、“ other=other.val ”这个语句中,other 在等号左边出现,是否可以认为 other 因此成为__add__的局部变量?
2、实例 y 对应的是__add__方法的 other 参数,从输出来看 other 变量在执行 x+y 前后已经发生了变化,那为何实例 y 在执行 x+y 后并没有变成 9,其地址始终不变?谢谢
def __init__(self,val):
self.val=val
def __add__(self,other):
if isinstance(other,a):
print("other 变量变化前 other=",other) #语句 1
other=other.val
print("other 变量变化后 other=",other) #语句 2
return a(self.val+other)
x=a(8)
y=a(9)
print("x+y 之前 y=",y) #语句 3
print("x+y=",x+y)
print("x+y 之后 y=",y) #语句 4
上面代码的输出如下:
x+y 之前 y= <__main__.a object at 0x01F16270>
other 变量变化前 other= <__main__.a object at 0x01F16270>
other 变量变化后 other= 9
x+y= <__main__.a object at 0x01F16290>
x+y 之后 y= <__main__.a object at 0x01F16270>
我的问题是:
1、“ other=other.val ”这个语句中,other 在等号左边出现,是否可以认为 other 因此成为__add__的局部变量?
2、实例 y 对应的是__add__方法的 other 参数,从输出来看 other 变量在执行 x+y 前后已经发生了变化,那为何实例 y 在执行 x+y 后并没有变成 9,其地址始终不变?谢谢