LoginSignup
0
0

More than 3 years have passed since last update.

pythonのグローバル変数を操作するときの話

Last updated at Posted at 2020-10-26

グローバル変数とローカル変数

pythonで実装中に何度かつまずいたので、自分用にメモ。
このコードが以下の結果を返すことは理解できる。

x = 1

def func1():
    print(x)

def func2():
    x = "hoge"
    print(x)

func1()
func2()

>>> 1
>>> hoge

pythonでは変数を参照するとき、ローカルスコープ内部で宣言されていない場合グローバルスコープを参照しに行く。

また、ローカルスコープで変数を書き換える前に変数が宣言されていない場合エラーを返す。

def func3():
    y += 1
    y = 5
    print(y)

func3()

>>> Traceback (most recent call last):
>>>   File "/test.py", line 8, in <test>
>>>     func3()
>>>   File "/test.py", line 4, in func3
>>>     y += 1
>>> UnboundLocalError: local variable 'y' referenced before assignment

ここまでは理解していたが、グローバル変数が絡むと途端に混乱してしまった。
つまり、グローバル変数として宣言されている変数を操作する場合は明示的に宣言せねばならず、普通にかくとエラーが返ってくる。

x = 1

def func4():
    x += 1 #この時点ではまだxを参照できない
    x = 5 #この段階でローカルスコープに変数xが追加される
    print(x)

func4()

>>> Traceback (most recent call last):
>>>   File "/test.py", line 8, in <test>
>>>     func4()
>>>   File "/test.py", line 4, in func4
>>>     x += 1 
>>> UnboundLocalError: local variable 'x' referenced before assignment

じゃあどうしたらいいの

解決方法は簡単で、グローバル変数を使う時はちゃんとグローバル変数であることを明示しましょうねって話。

x = 1

def func5():
    global x #グローバル変数であることを明示
    x += 1 
    print(x)

def func6():
    x = 10 #ローカル変数であることを明示
    x += 1
    print(x)

func5()
func6()

>>> 2
>>> 11
0
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
0
0