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