From 98682c7a8792e7e79e487fea5024d25cee5aa310 Mon Sep 17 00:00:00 2001
From: nsfisis contained unnecessary whitespaces inside it
---
.../2021-10-02/python-unbound-local-error/index.html | 18 ++++++------------
1 file changed, 6 insertions(+), 12 deletions(-)
(limited to 'public/posts/2021-10-02/python-unbound-local-error')
diff --git a/public/posts/2021-10-02/python-unbound-local-error/index.html b/public/posts/2021-10-02/python-unbound-local-error/index.html
index 27c2d05..0516d6f 100644
--- a/public/posts/2021-10-02/python-unbound-local-error/index.html
+++ b/public/posts/2021-10-02/python-unbound-local-error/index.html
@@ -60,15 +60,13 @@
Python でクロージャを作ろうと、次のようなコードを書いた。
- def f():
+ def f():
x = 0
def g():
x += 1
g()
-f()
-
+f()
関数gから 関数fのスコープ内で定義された変数xを参照し、それに 1 を足そうとしている。 これを実行するとx += 1の箇所でエラーが発生する。
@@ -84,8 +82,7 @@ f()
local変数xが代入前に参照された、とある。これは、fのxを参照するのではなく、新しく別の変数をg内に作ってしまっているため。 前述のコードを宣言と代入を便宜上分けて書き直すと次のようになる。varを変数宣言のための構文として擬似的に利用している。
- # 注: var は正しい Python の文法ではない。上記参照のこと
+ # 注: var は正しい Python の文法ではない。上記参照のこと
def f():
var x # f の local変数 'x' を宣言
x = 0 # x に 0 を代入
@@ -94,21 +91,18 @@ var x # g の local変数 'x' を宣言
# たまたま f にも同じ名前の変数があるが、それとは別の変数
x += 1 # x に 1 を加算 (x = x + 1 の糖衣構文)
# 加算する前の値を参照しようとするが、まだ代入されていないためエラー
-g()
-
+g()
当初の意図を表現するには、次のように書けばよい。
-
- def f():
+ def f():
x = 0
def g():
nonlocal x ## (*)
x += 1
-g()
-
+g()
(*)のように、nonlocalを追加する。これにより一つ外側のスコープ (gの一つ外側 =f) で定義されているxを探しに行くようになる。
--
cgit v1.2.3-70-g09d2