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
Kuonji
V2EX  ›  Python

局部变量疑惑,为什么这里的不用 global

  •  
  •   Kuonji · 2019-04-21 22:15:04 +08:00 · 2070 次点击
    这是一个创建于 1803 天前的主题,其中的信息可能已经有所发展或是发生改变。

    c = {}

    def foo():
    	#global c
    	c['a'] = 1
    

    执行 foo()后,输出 c,加不加 global,输出都一样 out:{'a': 1}

    6 条回复    2019-04-22 10:52:15 +08:00
    n329291362
        1
    n329291362  
       2019-04-21 22:37:39 +08:00
    LEGB 原则
    TJT
        2
    TJT  
       2019-04-22 00:07:55 +08:00
    因为你只是调用了的 a 对象的 __setitem__ 方法,没有对 a 重新赋值,自然也不需要 global。
    Vegetable
        3
    Vegetable  
       2019-04-22 01:22:26 +08:00
    global 是将局部作用域的局部变量,拿到外边去,成为全局变量.
    你这个例子是直接操作了全局变量.两回事.
    dangyuluo
        4
    dangyuluo  
       2019-04-22 05:43:17 +08:00
    @TJT 是调用了`c`对象的`__setitem__`
    codechaser
        5
    codechaser  
       2019-04-22 09:49:28 +08:00
    如果只是引用外层变量的话,是不需要 global 的。但是要是涉及到赋值时则需要使用 global,前提是那个全局变量已经被引入到了当前作用域。
    ```python
    def f():
    print(s)

    #不会出错
    s = "foo"
    f()

    def foo():
    s = 100
    print(s)

    #也不会出错
    foo()

    def test():
    print(s)
    #这里会出错
    s = 555
    print(s)

    test()
    # local variable 's' referenced before assignment
    ```

    > We only need to use global keyword in a function if we want to do assignments / change them. global is not needed for printing and accessing. Why? Python “ assumes ” that we want a local variable due to the assignment to s inside of f(), so the first print statement throws this error message. Any variable which is changed or created inside of a function is local, if it hasn ’ t been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword “ global ”, as can be seen in the following
    Outliver0
        6
    Outliver0  
       2019-04-22 10:52:15 +08:00
    python 中的可变类型和不可变类型
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2998 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 14:50 · PVG 22:50 · LAX 07:50 · JFK 10:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.