我曾經用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