python的作用域並不是哪裏都能訪問的,類似於Java,分全局和局部,python變量的作用域大概分爲以下四類:
L(local) 局部作用域
E(Enclosing) 閉包函數外的函數中
G(Global) 全局作用域
B(Built-in) 內建作用域
遵循LEGB原則:以 L –> E –> G –>B 的規則查找,即:在局部找不到,便會去局部外的局部找(例如閉包),再找不到就會去全局找,再者去內建中找。
x = int(2.9) # 內建作用域
g_count = 0 # 全局作用域
def outer():
o_count = 1 # 閉包函數外的函數中
def inner():
i_count = 2 # 局部作用域
在python中,模塊(module),類(class)、函數(def、lambda)會產生新的作用域,其他代碼塊是不會產生作用域的,也就是說,類似條件判斷(if…..else)、循環語句(for x in data)、異常捕捉(try…catch)等的變量是可以全局使用的
dataList = [1, 2, 3, 4]
for data in dataList:
a = 1 #for循環中的變量a
b = data + a
print(a) #在函數外也可視爲全局變量使用
全局變量是指在函數外的變量,可以在程序全局使用,局部變量是指定義在函數內的變量,只能在函數內被聲明使用
若內部作用域的想要修改外部作用域的變量,就要使用global關鍵字:參考一下代碼
1、未使用global關鍵字
a = 1
def demo():
# IDE提示a = 123:This inspection detects shadowing names defined in outer scopes
# 大概意思是給變量取的這個名字,可能會衝突,它是函數外部的變量
a = 123
print(a)
demo()
print(a)
運行結果是
123
1
全局變量a的值還是1,沒有被改變
2、使用global關鍵字
a = 1
def demo():
global a
a = 123
print(a)
demo()
print(a)
運行結果是
123
123
全局變量a的值被修改
nonlocal 關鍵字的使用方法和global關鍵字類似,修改嵌套作用域(enclosing 作用域,外層非全局作用域)中的變量
def outer():
num = 10
def inner():
nonlocal num # nonlocal關鍵字聲明
num = 100
print(num)
inner()
print(num)
outer()
運行結果爲
100
100
閉包函數外的變量num值被修改