请参阅以下代码:
def good():
foo[0] = 9 # why this foo isn't local variable who hides the global one
def bad():
foo = [9, 2, 3] # foo is local, who hides the global one
for func in [good, bad]:
foo = [1,2,3]
print('Before "{}": {}'.format(func.__name__, foo))
func()
print('After "{}": {}'.format(func.__name__, foo))
Run Code Online (Sandbox Code Playgroud)
结果如下:
# python3 foo.py
Before "good": [1, 2, 3]
After "good": [9, 2, 3]
Before "bad" : [1, 2, 3]
After "bad" : [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
因为你没有设置foo,所以你在 foo中得到了一些东西(确切地说是foo [0]).
在bad你创建一个新的变量foo.在good你做的事情foo.set(0, 9)(设置项目0到值9).哪个使用变量,而不是定义新名称.