2014/02/13

Python 3.3 Global & Nonlocal

Global:將變數設定為全域變數,使得變數能夠在類別或模組內可以存取
Nonlocal:將變數設定為範圍變數,僅只在特定範圍內可以存取


def test():
    x = 0

    def myNonlocal():
        nonlocal x
        x = 10
        print(x)

    def myGlobal():
        global x
        x = 100
        print(x)

    print(x)
    myNonlocal()
    myGlobal()
    print(x)

test()





參考資料:
http://docs.python.org/3/reference/simple_stmts.html#global
http://docs.python.org/3/reference/simple_stmts.html#nonlocal