0
1

More than 3 years have passed since last update.

内部関数を用いた際の変数スコープ

Posted at

何回か使うけど、外出しの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}

使いどころがあるのかは知らない!

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1