查找namespace的順序與權限
查找順序 Local -> Enclosed -> Global -> Built-in
低層不能改變高層的值,只能讀取。
x = 1
def outer():
x = 10
outer()
print(x) # 1
因為Local沒有x所以會往Global找x。
x = 1
def outer():
print(x) # 1
outer()
print(x) # 1
但要真的改變就要加上global
x = 1
def outer():
global x
x = 10
outer()
print(x) # 10
在enclosed中的要加上nonlocal
def outer():
x = 1 # enclosed scope
def inner():
x = 10 # local scope
print(x) # 1
outer()
def outer():
x = 1 # enclosed scope
def inner():
nonlocal x
x = 10 # local scope
print(x) # 10
outer()