Possible Duplicate:
Python variable scope question
Python nested function scopes
我对下面的代码感到困惑
def func():
a=10
def func2():
print a
a=20
func2()
print a
func()
在python 2.7中,运行上述代码时,python会报错,UnboundLocalError
,在 func2
中投诉,当 print a
, 'a' 在赋值之前被引用
但是,如果我评论a=20
在func2
, 一切顺利。 Python 将打印两行 10;即,以下代码是正确的。
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
}
}
可以非常清楚地区分局部变量和外部变量。
最佳答案
通过添加行a=20
,Python分析代码并发现a
也被用作局部变量名。在这种情况下,您尝试打印尚 undefined variable 的值(在 func2
中)。
如果没有该行,Python 将使用 func
范围内的 a
值(该值在 func2
内仍然有效)。您是对的,这与 C/C++ 中的示例不同。
关于python - 关于Python中另一个函数内部的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12051987/