Python 函式的作用域

2022-03-17 16:02:50 字數 1672 閱讀 8652

python中的作用域有4種:

名稱介紹

llocal,區域性作用域,函式中定義的變數;

eenclosing,巢狀的父級函式的區域性作用域,即包含此函式的上級函式的區域性作用域,但不是全域性的;

bgloba,全域性變數,就是模組級別定義的變數;

gbuilt-in,系統固定模組裡面的變數,比如int, bytearray等。

搜尋變數的優先順序順序依次是(legb):

作用域區域性 > 外層作用域 > 當前模組中的全域性 > python內建作用域。

number = 10             # number 是全域性變數,作用域在整個程式中

def test():

print(number)

a = 8 # a 是區域性變數,作用域在 test 函式內

print(a)

test()

執行結果:

108

def outer():

o_num = 1 # enclosing

i_num = 2 # enclosing

def inner():

i_num = 8 # local

print(i_num) # local 變數優先

print(o_num)

inner()

outer()

執行結果:

81

num = 1

def add():

num += 1

print(num)

add()

執行結果:

unboundlocalerror: local variable 'num' referenced before assignment

如果想在函式中修改全域性變數,需要在函式內部在變數前加上 global 關鍵字

num = 1                    # global 變數

def add():

global num # 加上 global 關鍵字

num += 1

print(num)

add()

執行結果:

2

同理,如果希望在內層函式中修改外層的 enclosing 變數,需要加上 nonlocal 關鍵字

def outer():

num = 1 # enclosing 變數

def inner():

nonlocal num # 加上 nonlocal 關鍵字

num = 2

print(num)

inner()

print(num)

outer()

執行結果:

22

1.只有模組、類、及函式才能引入新作用域;

2.對於乙個變數,內部作用域先宣告就會覆蓋外部變數,不宣告直接使用,就會使用外部作用域的變數(這時只能檢視,無法修改);

3.如果內部作用域要修改外部作用域變數的值時, 全域性變數要使用 global 關鍵字,巢狀作用域變數要使用 nonlocal 關鍵字。

Python 函式作用域

python中變數作用域分4種情況 x max 1,6 max為系統變數,它的作用域為python的所有模組 y 1 y為全域性變數,它的作用域為當前模組 defouter i 3 i的作用域為當前函式,包括巢狀函式 definner count 2 count為區域性變數,作用域只在當前函式有效函...

Python中的函式作用域

在python中,乙個函式就是乙個作用域 name xiaoyafei def change name name 肖亞飛 print 在change name裡的name name change name 呼叫函式 print 在外面的name name 執行結果如下 在change name裡的n...

python學習 函式 作用域

定義函式 def do nothing pass 呼叫函式 do nothing none 是python中的乙個特殊的值,它和false,空值是有區別的。注意函式引數的傳入。使用 收集位置引數 當引數被用在函式內部時,星號將一組可變數量的位置引數集合成引數值的元組。def print args a...