Help us understand the problem. What is going on with this article?

Pythonのクロージャについて

More than 1 year has passed since last update.

クロージャ(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??
ryicoh
Go、GraphQLが好き、クラウドとかk8sとかも最近触ってないけど好き
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした