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

2019-04-21 22:15:04 +08:00
 Kuonji

c = {}

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

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

2081 次点击
所在节点    Python
6 条回复
n329291362
2019-04-21 22:37:39 +08:00
LEGB 原则
TJT
2019-04-22 00:07:55 +08:00
因为你只是调用了的 a 对象的 __setitem__ 方法,没有对 a 重新赋值,自然也不需要 global。
Vegetable
2019-04-22 01:22:26 +08:00
global 是将局部作用域的局部变量,拿到外边去,成为全局变量.
你这个例子是直接操作了全局变量.两回事.
dangyuluo
2019-04-22 05:43:17 +08:00
@TJT 是调用了`c`对象的`__setitem__`
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
2019-04-22 10:52:15 +08:00
python 中的可变类型和不可变类型

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

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

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

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

© 2021 V2EX