请教关于变量作用域的问题

2017-08-09 20:27:22 +08:00
 saximi
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,其地址始终不变?谢谢
1460 次点击
所在节点    Python
3 条回复
hjq98765
2017-08-09 21:35:37 +08:00
缩进乱掉了
lrxiao
2017-08-10 00:26:01 +08:00
传进去的都是可重绑定的引用 绑定到了新对象
jmc891205
2017-08-10 10:51:28 +08:00
1. other 是__add__的参数里定义的,所以它的作用域只在__add__()里有效
2. other 和 y 本身是不同的两个引用,只是他们引用的是同一个东西罢了。你看看 id(other)和 id(y),应该是不同的。所以你更改了 other,让它去引用其他的东西,并不会影响到 y。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/381764

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX