c = {}
def foo():
#global c
c['a'] = 1
执行 foo()后,输出 c,加不加 global,输出都一样 out:{'a': 1}
1
n329291362 2019-04-21 22:37:39 +08:00
LEGB 原则
|
2
TJT 2019-04-22 00:07:55 +08:00
因为你只是调用了的 a 对象的 __setitem__ 方法,没有对 a 重新赋值,自然也不需要 global。
|
3
Vegetable 2019-04-22 01:22:26 +08:00
global 是将局部作用域的局部变量,拿到外边去,成为全局变量.
你这个例子是直接操作了全局变量.两回事. |
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 |
6
Outliver0 2019-04-22 10:52:15 +08:00
python 中的可变类型和不可变类型
|