Python のスコープについて
こんな認識であってるのかなぁ?と思ってツラツラ書いてみる
関数はスコープ持ってるのでそのまま代入しても global の値は変更されない。
In [1]: foo = 0 In [2]: def bar(): ...: foo = 1 ...: In [3]: print foo 0 In [4]: bar() In [5]: print foo 0
(関数内で global で宣言すればOKだけど)
In [2]: def bar(): ...: global foo ...: foo = 1 ...:
でもこんな書き方は出来ない
In [12]: def bar(): ....: global foo = 1 ------------------------------------------------------------ File "<ipython console>", line 2 global foo = 1 ^ SyntaxError: invalid syntax
値が代入されて有効になる(宣言時に初期化とかされない)
In [1]: def bar(): ...: global j ...: In [2]: bar() In [3]: print j --------------------------------------------------------------------------- NameError Traceback (most recent call last) /home/yoshiori/<ipython console> in <module>() NameError: name 'j' is not defined
ブロックスコープとかは無いので for で宣言(代入)した値も for 文の外からアクセス出来る。
In [6]: for i in range(10): ...: print i ...: 0 1 2 3 4 5 6 7 8 9 In [7]: print i 9
同じ理屈で if 文の中で宣言(代入)した値も if 文の外からアクセス出来る。
In [8]: if True: ...: hoge = 100 ...: In [9]: print hoge 100
なんというか代入前に参照すると not defined じゃなく値の割り当てがされてないよ的な事を言われる
In [4]: def bar(): ...: print hoge ...: hoge = "hoge" ...: In [5]: bar() --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) /home/yoshiori/<ipython console> in <module>() /home/yoshiori/<ipython console> in bar()
js っぽい感じ?