Function Scope

區域與全域

函式幫助我們區分了程式的責任範圍,非常的方便,但是在函式中的變數可能跟函式外的變數命名相同, 當執行函式時,應該執行函式內的變數還是函式外的變數呢?

我們來看看以下的範例:

name = 'Tom'

def hello1():
    name = 'Mary'
    print('in hello1(), name is ' + name)
    
def hello2():
    print('in hello2(), name is ' + name)
    
def hello3():
    global name
    name = 'Mike'
    print('in hello3(), name is ' + name)
    
    
hello1()
print('Outside of function, name is ' + name)
hello2()
print('Outside of function, name is ' + name)
hello3()
print('Outside of function, name is ' + name)

變數的作用域

  1. 變數的宣告是在指派時發生,如x=10

  2. 當變數宣告在上層的區塊中,其下層的區塊皆可以使用,函式也可以,以此類推

  3. 函式中如果有宣告變數,那麼就是函式的區域變數,如果沒有宣告,使用的變數就會從外層去找

  4. 函式中如果要使用全域變數,且要重新指派值給它,則我們必須先以global宣告

  5. 變數請依照函式(Local function),外包函式(Enclosing function),全域(Global),內建(Builtin)的順序來尋找

Last updated

Was this helpful?