我曾经用C,C#和Java编程。现在我正在使用Python一段时间,但是我在理解变量作用域时遇到了一些问题,这对我来说现在非常困惑。例如:混淆变量作用域(来自外部作用域的阴影变量)
def f1():
print(spam) # spam magically come from outer scope. ok...
def f2():
spam = "bbb" # assignment shadows variable from outer scope (logical result of f1)
print(spam) # printing local spam variable
def f3():
print(spam) # ERROR: unresolved reference 'spam'
spam = "ccc" # in f1 function everything was fine but adding assignment AFTER
# printing (in opposite to f2 function) causes error in line above
def f4():
print(spam) # nothing wrong here, assignment line below is commented
# spam = "ccc"
spam = "aaa"
为什么地球上的功能可能会超出其范围之外的变量? 为什么从外部范围的阴影变量是好的,但只有我们以前没有使用它?
你肯定你会在'f3'中得到'未解决的参考错误'?我期望在赋值之前引用错误'UnboundLocalError:本地变量'垃圾邮件',这是相当自我解释的。 – kazemakase
'f2'发生了什么变化'垃圾'从'aaa'到'bbb' – mtkilic
@kazemakase你说得对,我写的错误是从IDE而不是运行时 – user3616181