次のコードについて混乱しています
def func():
a=10
def func2():
print a
a=20
func2()
print a
func()
Python 2.7 では、上記のコードを実行すると、代入前に 'a' が参照されている場合UnboundLocalError
、 python はエラー を返します。func2
print a
しかし、私がコメントa=20
するとfunc2
、すべてがうまくいきます。Python は 10 行を 2 行出力します。つまり、次のコードは正しいです。
def func():
a=10
def func2():
print a
func2()
print a
func()
なんで?他の言語では、c/c++ のように
{
a=10
{
cout<<a<<endl //will give 10
a=20 //here is another a
cout<<a<<endl //here will give 20
}
}
ローカル変数と外部変数は非常に明確に区別できます。