何回か使うけど、外出しのmethodにする必要もないなという場合に使う関数の入れ子。
def hoge():
def fuga():
pass
これを使うときに変数の扱いがどうなるのかなと思ったので検証。
ローカル変数
def hoge():
x = 1
def fuga():
x = 3
fuga()
print(x)
実行結果
hoge()
1
ローカル変数の場合はそれぞれ別の変数として扱われるようだ。当然っちゃ当然。
ただ、これはnonlocal
宣言で変更することができる。
def hoge():
x = 1
def fuga():
nonlocal x
x = 3
fuga()
print(x)
実行結果
hoge()
3
クラス変数
class Sample:
def __init__(self):
self.hoge = None
def hoge():
smp = Sample()
smp.hoge = "abcde"
def fuga():
smp.hoge = "fghijk"
fuga()
print(amp.__dict__)
実行結果
hoge()
{'hoge': 'fghijk'}
クラス変数の場合はグローバル扱いになるのかな。
おまけ
これを使って条件によって別の値をクラス変数に入れたいときにコードをスッキリできる
class Sample():
def __init__(self):
self.hoge = None
self.fuga = None
def hoge(list):
smp = Sample()
def set_val(val1, val2):
smp.hoge = val1
smp.fuga = val2
if len(list) == 1:
set_val(list[0], None)
else:
set_val(list[0], list[1])
print(smp.__dict__)
実行結果
hoge(['aaaa', 'bbbb'])
{'hoge': 'aaaa', 'fuga': 'bbbb'}
hoge(['cccc'])
{'hoge': 'cccc', 'fuga': None}
使いどころがあるのかは知らない!