内部関数(inner function)
pythonでは、関数内部に関数を定義することが可能です。
def outer_function(): """ 外側の関数 """ print('outer') def inner_function(): """ 内側の関数 """ print('inner') inner_function() outer_function()
先ほどの関数オブジェクトの考え方を応用すると、以下のような使い方も可能です。
関数オブジェクトとして代入する場合は丸カッコをつけないでください。
def outer_function(): """ 外側の関数 """ print('outer') def inner_function(): """ 内側の関数 """ print('inner') # 内側の関数をオブジェクトとしてreturnする f = inner_function return f f = outer_function() # 受け取った内側の関数を実行する f() # innerが出力される
nonlocal宣言
内側で定義した関数から外側のローカル関数を参照することが可能です。
内側の関数で外側のローカル変数を変更したい場合、nonlocal宣言を記述することでできるようになります。
global宣言と似ていますね。
def outer_function(): """ 外側の関数 """ x = 100 print(x) # 100が出力される def inner_function(): """ 内側の関数 """ nonlocal x x = 200 print(x) # 200が出力される inner_function() print(x) # 200が出力される outer_function()
外側の関数の変数が内部関数で変更されたことが確認できます。