1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Python] Scopeについて(勉強用)

Posted at

pythonのclassを学習していく中でScopeという機能を新たに学習したので、実際にコードを書いて中身を確認していく。

qiita.py

def scope_test():

    def do_local(): 
        Student = "Taniyama"
    
    def do_nonlocal():
        nonlocal Student
        Student= "Takagi"
    
    def do_global():
        global Student
        Student = "Kawai"

    Student = "Katayama"

    do_local()
    print("After local assignment:",Student) #not assigned
    do_nonlocal()
    print("After nonlocal assignment:",Student) #assigned
    do_global()
    print("After global assignment",Student) #not assigned

scope_test()
print("In global scope:",Student)

出力

qiita.py
After local assignment: Katayama
After nonlocal assignment Takagi
After global assignment Takagi
In global scope Kawai

1 関数scope_testを出力した際に、子関数のdo_localが処理され、変数Studentに"Taniyama"が代入されているが、親関数の中で"Katayama"と定義されているので、"Katayama"と出力される。"Taniyama"はあくまでdef do_local():内の"Student"が"Taniyama"になっただけの処理(ローカル変数)

2 nonlocalを使うことで親関数の変数を参照でき、親関数のStudentにdo_nonlocalで定義した"Takagiが代入され出力される。(ノンローカル変数)

3 globalを使うことで、global変数が変更されるが、親関数には影響を与えないため、scope_test内のStudentはdo_nonlocalで代入された"Takagi"が出力される。(グローバル変数)

4 関数の外の処理ではdo_global()で定義されたグローバル変数Student = "Kawai"が代入されているため、モジュール内ではStudent = "Kawai"となり、出力される。

そもそもスコープとは、プログラム内で、変数や関数が有効な範囲を指す。

スコープには3種類あり、グローバルスコープ、ノンローカルスコープ、ローカルスコープがある。

グローバルスコープ:
 プログラム全体からアクセスが可能

ノンローカルスコープ:
 ネストされた親関数の変数を参照、変更することができる。グローバル変数には影響しない。

ローカルスコープ:
 関数内で定義され、その範囲内のみで有効なもの。

これらに分けて変数を設定すると有効範囲が明確になり、意図せず変数が上書きされるリスクを減らせる。また可読性の向上。

基本的にglobalnonlocalを使用しなけらばローカル変数として扱われ、関数内でのみ有効

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?