1
0

More than 3 years have passed since last update.

分かりにくい nonlocal

Last updated at Posted at 2021-01-07

多分、使わない nonlocal だけど

Python 3.9.1 のドキュメント
  9.2.1. スコープと名前空間の例

が読みにくかったので、自分なりに解釈したコメントを追加。

def scope_test():
    def do_local():
        spam = "local spam"
            # do_local の spam に代入
            #   何処からも参照されないので無意味な処理
            #   動作説明には必要

    def do_nonlocal():
        nonlocal spam
            # do_nonlocal には spam が無い、と宣言
            #   外側にある関数 (scope_test) の spam を使う
            #   global の spam は使わない
        spam = "nonlocal spam"

    def do_global():
        global spam
            # global の spam を使う、と宣言
        spam = "global spam"

    # 以下の "spam" は scope_test のもの
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

# 以下の "spam" は global のもの
scope_test()
print("In global scope:", spam)

こんな感じかな。 global と nonlocal は参照範囲が排他になっている。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0