Python 變數作用域
阿新 • • 發佈:2018-12-14
– Start 關於變數,Python 有個著名的 LEGB 規則。
Local - 區域性變數
def outer():
def inner():
v = 1 # Local
print(f'v = {v}')
inner()
outer()
Enclosing - 閉包變數
def outer():
v = 1 # Enclosing
def inner():
print(f'v = {v}')
inner()
outer()
Global - 全域性變數
v = 1 # Global def outer(): def inner(): print(f'v = {v}') inner() outer()
Built-in - 內建變數
def outer():
def inner():
# False is Built-in
print(f'v = {False}')
inner()
outer()
查詢規則
Python 會按照 Local -> Enclosing -> Global -> Built-in 的順序搜尋變數。
v = 1 # Global def outer(): v = 2 # Enclosing def inner(): v = 3 # Local print(f'Local, v = {v}') inner() print(f'Enclosing, v = {v}') outer() print(f'Global, v = {v}')
不能修改其他作用域變數
v = 1 # Global
def outer():
v = 2 # Enclosing
def inner():
v += 10 # 修改變數,報錯
print(f'Local, v = {v}')
inner()
print(f'Enclosing, v = {v}')
outer()
print(f'Global, v = {v}')
一定要修改呢?
v = 1 # Global def outer(): v = 2 # Enclosing def inner(): nonlocal v v += 10 # 修改 Enclosing 變數 print(f'Local, v = {v}') inner() print(f'Enclosing, v = {v}') outer() print(f'Global, v = {v}')
v = 1 # Global
def outer():
v = 2 # Enclosing
def inner():
global v
v += 10 # 修改 Global 變數
print(f'Local, v = {v}')
inner()
print(f'Enclosing, v = {v}')
outer()
print(f'Global, v = {v}')
– 更多參見: – 聲 明:轉載請註明出處 – Last Updated on 2018-10-10 – Written by ShangBo on 2018-10-10 – End