LoginSignup
16
16

More than 1 year has passed since last update.

Pythonのクロージャについて

Last updated at Posted at 2018-04-13

クロージャ(Closure)

関数の中の関数のこと
外の関数のスコープである変数にアクセスできる。

def outer():
  val = "Hello World!!"
  def inner():
      print(val)  # 関数'outer'外の変数'val'にアクセス可能
  inner()

outer()
# >>> Hello World!!

注意点

スコープに注意しなければならない。
pythonでは現在の関数のスコープから変数を参照する。

# "Goodbye World??"出力したい
def outer():
  val = "Hello World!!"  # スコープ: 'outer'
  def inner():
      val = "Goodbye World??"  # スコープ: 'inner'
  inner()
  print(val)  # 'outer'のvalを参照する
              # innerのvalは新しく生成されたため別のオブジェクト

outer()
# >>> Hello World!!

解決方法

nonlocalを入れるだけ

def outer():
  val = "Hello World!!"
  def inner():
      nonlocal val  # nonlocalを入れる
      val = "Goodbye World??"
  inner()
  print(val)

outer()
# >>> Goodbye World??
16
16
1

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
16
16