推荐学习书目
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 · Aug 9, 2017 · 1948 views
    This topic created in 3236 days ago, the information mentioned may be changed or developed.
    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 replies    2017-08-10 10:51:28 +08:00
    hjq98765
        1
    hjq98765  
       Aug 9, 2017
    缩进乱掉了
    lrxiao
        2
    lrxiao  
       Aug 10, 2017
    传进去的都是可重绑定的引用 绑定到了新对象
    jmc891205
        3
    jmc891205  
       Aug 10, 2017
    1. other 是__add__的参数里定义的,所以它的作用域只在__add__()里有效
    2. other 和 y 本身是不同的两个引用,只是他们引用的是同一个东西罢了。你看看 id(other)和 id(y),应该是不同的。所以你更改了 other,让它去引用其他的东西,并不会影响到 y。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2566 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 15:14 · PVG 23:14 · LAX 08:14 · JFK 11:14
    ♥ Do have faith in what you're doing.