From d30dfc89bf1b673b2fdc0638766b930adaec228c Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sat, 29 Mar 2025 00:47:55 +0900 Subject: feat(blog/nuldoc): migrate syntax highlighter from highlight.js to shiki.js --- .../python-unbound-local-error/index.html | 55 ++++++++++++---------- 1 file changed, 30 insertions(+), 25 deletions(-) (limited to 'vhosts/blog/public/posts/2021-10-02/python-unbound-local-error') diff --git a/vhosts/blog/public/posts/2021-10-02/python-unbound-local-error/index.html b/vhosts/blog/public/posts/2021-10-02/python-unbound-local-error/index.html index 91ec5d0a..f3a11356 100644 --- a/vhosts/blog/public/posts/2021-10-02/python-unbound-local-error/index.html +++ b/vhosts/blog/public/posts/2021-10-02/python-unbound-local-error/index.html @@ -14,8 +14,7 @@ 【Python】 クロージャとUnboundLocalError: local variable 'x' referenced before assignment|REPL: Rest-Eat-Program Loop - - +
@@ -78,13 +77,15 @@ 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 の箇所でエラーが発生する。 @@ -100,27 +101,31 @@ f() 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.2.3-70-g09d2