的問題是,Python的希望你是明確的,你想成爲隱式的。 Python使用的execution model將綁定名稱綁定到最接近的可用,範圍爲。
def Test(value):
# Local Scope #1
def innerFunc():
# Local Scope #2
print value
# No immediate local in Local Scope #2 - check up the chain
# First find value in outer function scope (Local Scope #1).
# Use that.
innerFunc()
def TestWithAssignment(value):
# Local Scope #1
def innerFunc():
# Local Scope #2
print value
# Immediate local variable found in Local Scope #2.
# No need to check up the chain.
# However, no value has been assigned to this variable yet.
# Throw an error.
value = "Changed value"
innerFunc()
沒有(據我所知)走了在Python 2.x的範圍的方式 - 你必須globals()
和locals()
- 但全球和局部範圍之間的任何範圍無法訪問(如果這不是真的,我會愛待糾正)。
但是,您可以通過局部變量value
到你內心的局部範圍:
def TestWithAssignment(value):
def innerFunc(value):
print value
# Immediate local **and assigned now**.
value = "Changed value"
# If you need to keep the changed value
# return value
innerFunc(value)
# If you need to keep the changed value use:
# value = innerFunc(value)
在Python 3中,你可以用來指包含範圍內(感謝@Thomas k上的新nonlocal
聲明)。
def TestWithAssignment(value):
def innerFunc():
nonlocal value
print value
value = "Changed value"
innerFunc()
http://stackoverflow.com/q/855493/287976的可能的複製 – brandizzi