From 4681e861efcdf9b0b73e3803e70712bc55162863 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sat, 8 Aug 2026 10:38:18 +0900 Subject: feat(slides): improve slide controller --- .../python-unbound-local-error/index.html | 51 ++++++++++++---------- 1 file changed, 27 insertions(+), 24 deletions(-) (limited to 'services/nuldoc/public/blog/posts/2021-10-02/python-unbound-local-error/index.html') diff --git a/services/nuldoc/public/blog/posts/2021-10-02/python-unbound-local-error/index.html b/services/nuldoc/public/blog/posts/2021-10-02/python-unbound-local-error/index.html index a38d197c..aa63127f 100644 --- a/services/nuldoc/public/blog/posts/2021-10-02/python-unbound-local-error/index.html +++ b/services/nuldoc/public/blog/posts/2021-10-02/python-unbound-local-error/index.html @@ -15,7 +15,7 @@ 【Python】 クロージャとUnboundLocalError: local variable 'x' referenced before assignment|REPL: Rest-Eat-Program Loop - +
@@ -75,13 +75,14 @@ Python でクロージャを作ろうと、次のようなコードを書いた。

-
def f(): -
x = 0 -
def g(): -
x += 1 -
g() -
-
f()
+
def f():
+    x = 0
+    def g():
+        x += 1
+    g()
+
+f()
+

関数 g から 関数 f のスコープ内で定義された変数 x を参照し、それに 1 を足そうとしている。 これを実行すると x += 1 の箇所でエラーが発生する。 @@ -95,27 +96,29 @@ local変数 x が代入前に参照された、とある。これは、fx を参照するのではなく、新しく別の変数を g 内に作ってしまっているため。前述のコードを宣言と代入を便宜上分けて書き直すと次のようになる。var を変数宣言のための構文として擬似的に利用している。

-
# 注: var は正しい Python の文法ではない。上記参照のこと -
def f(): -
var x # f の local変数 'x' を宣言 -
x = 0 # x に 0 を代入 -
def g(): # f の内部関数 g を定義 -
var x # g の local変数 'x' を宣言 -
# たまたま f にも同じ名前の変数があるが、それとは別の変数 -
x += 1 # x に 1 を加算 (x = x + 1 の糖衣構文) -
# 加算する前の値を参照しようとするが、まだ代入されていないためエラー -
g()
+
# 注: var は正しい Python の文法ではない。上記参照のこと
+def f():
+  var x           #  f の local変数 'x' を宣言
+  x = 0           #  x に 0 を代入
+  def g():        #  f の内部関数 g を定義
+      var x       #  g の local変数 'x' を宣言
+      #  たまたま f にも同じ名前の変数があるが、それとは別の変数
+      x += 1      #  x に 1 を加算 (x = x + 1 の糖衣構文)
+      #  加算する前の値を参照しようとするが、まだ代入されていないためエラー
+  g()
+

当初の意図を表現するには、次のように書けばよい。

-
def f(): -
x = 0 -
def g(): -
nonlocal x ## (*) -
x += 1 -
g()
+
def f():
+    x = 0
+    def g():
+        nonlocal x   ## (*)
+        x += 1
+    g()
+

(*) のように、nonlocal を追加する。これにより一つ外側のスコープ (g の一つ外側 = f) で定義されている x を探しに行くようになる。 -- cgit v1.3.1