以下(荒誕而是說明性的)代碼的工作通過突變在封閉函數定義的列表作爲預期:對象可變性對Python的作用域有什麼影響?
def outside1():
l = list('abcd')
def inside(a):
print "Before - %i: %r" % (id(l), l)
l.append(a)
print "After - %i: %r\n" % (id(l), l)
return inside
f = outside1()
[f(c) for c in 'efgh']
該代碼也可以表示,在一個封閉的範圍限定的不可變的是封閉範圍內的訪問:
def outside2():
t = tuple('abcd')
def inside():
print "%i: %r" % (id(t), t)
return inside
outside2()()
但是這個失敗local variable 't' referenced before assignment
:
def outside3():
t = tuple('abcd')
def inside(a):
print "Before - %i: %r" % (id(t), t)
t = t + (a,)
print "After - %i: %r\n" % (id(t), t)
return inside
f = outside3()
[f(c) for c in 'efgh']
可有人è xplain這裏發生了什麼?我的第一個猜測是,我可以進行變異,但不能指定爲封閉範圍,但是如果outside2
工作,我至少應該在打印聲明之前工作。
「Python在編譯時靜態檢測名稱的範圍」謝謝,這是簡短的答案; py3k的提示是一個不錯的獎勵。 – Finn 2012-03-23 14:17:53