diff options
| author | nsfisis <nsfisis@gmail.com> | 2023-03-15 01:36:13 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2023-03-15 01:36:58 +0900 |
| commit | 98682c7a8792e7e79e487fea5024d25cee5aa310 (patch) | |
| tree | fbf975077f5c1a6ff4f9eee68e4a4908eb7f54a0 /public/posts/2021-10-02/python-unbound-local-error/index.html | |
| parent | 1fa2ed103dc521698cff261c97ecf275708be58c (diff) | |
| download | blog.nsfisis.dev-98682c7a8792e7e79e487fea5024d25cee5aa310.tar.gz blog.nsfisis.dev-98682c7a8792e7e79e487fea5024d25cee5aa310.tar.zst blog.nsfisis.dev-98682c7a8792e7e79e487fea5024d25cee5aa310.zip | |
fix(nuldoc): <pre> contained unnecessary whitespaces inside it
Diffstat (limited to 'public/posts/2021-10-02/python-unbound-local-error/index.html')
| -rw-r--r-- | public/posts/2021-10-02/python-unbound-local-error/index.html | 18 |
1 files changed, 6 insertions, 12 deletions
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 でクロージャを作ろうと、次のようなコードを書いた。 </p> - <pre class="highlight" language="python" linenumbering="unnumbered"> - <code>def f(): + <pre class="highlight" language="python" linenumbering="unnumbered"><code>def f(): x = 0 def g(): x += 1 g() -f()</code> - </pre> +f()</code></pre> <p> 関数<code>g</code>から 関数<code>f</code>のスコープ内で定義された変数<code>x</code>を参照し、それに 1 を足そうとしている。 これを実行すると<code>x += 1</code>の箇所でエラーが発生する。 @@ -84,8 +82,7 @@ f()</code> local変数<code>x</code>が代入前に参照された、とある。これは、<code>f</code>の<code>x</code>を参照するのではなく、新しく別の変数を<code>g</code>内に作ってしまっているため。 前述のコードを宣言と代入を便宜上分けて書き直すと次のようになる。<code>var</code>を変数宣言のための構文として擬似的に利用している。 </p> - <pre class="highlight" language="python" linenumbering="unnumbered"> - <code># 注: var は正しい Python の文法ではない。上記参照のこと + <pre class="highlight" language="python" linenumbering="unnumbered"><code># 注: 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()</code> - </pre> +g()</code></pre> <p> 当初の意図を表現するには、次のように書けばよい。 </p> - <pre class="highlight" language="python" linenumbering="unnumbered"> - <code>def f(): + <pre class="highlight" language="python" linenumbering="unnumbered"><code>def f(): x = 0 def g(): nonlocal x ## (*) x += 1 -g()</code> - </pre> +g()</code></pre> <p> <code>(*)</code>のように、<code>nonlocal</code>を追加する。これにより一つ外側のスコープ (<code>g</code>の一つ外側 =<code>f</code>) で定義されている<code>x</code>を探しに行くようになる。 |
