V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
saximi
V2EX  ›  Python

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

  •  
  •   saximi · 2017-08-09 20:27:22 +08:00 · 1456 次点击
    这是一个创建于 2463 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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,其地址始终不变?谢谢
    3 条回复    2017-08-10 10:51:28 +08:00
    hjq98765
        1
    hjq98765  
       2017-08-09 21:35:37 +08:00
    缩进乱掉了
    lrxiao
        2
    lrxiao  
       2017-08-10 00:26:01 +08:00
    传进去的都是可重绑定的引用 绑定到了新对象
    jmc891205
        3
    jmc891205  
       2017-08-10 10:51:28 +08:00
    1. other 是__add__的参数里定义的,所以它的作用域只在__add__()里有效
    2. other 和 y 本身是不同的两个引用,只是他们引用的是同一个东西罢了。你看看 id(other)和 id(y),应该是不同的。所以你更改了 other,让它去引用其他的东西,并不会影响到 y。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1642 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:03 · PVG 01:03 · LAX 10:03 · JFK 13:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.