問題是在這篇文章的末尾。如何打印語句創建一個局部變量
第一個片段:空局部變量字典。
def outer():
x = 1
def inner():
print "Local variables: %s" % locals()
return inner()
print outer()
輸出: 局部變量:{}
第二片段:打印內()函數內部和創建本地變量條目。
def outer():
x = 1
def inner():
print x
print "Local variables: %s" % locals()
return inner()
print outer()
輸出:
1
Local variables: {'x': 1}
第三片段:
def outer():
x = 1
def inner():
print x
print "Local variables: %s" % locals()
del x
return inner()
print outer()
輸出::
>>> outer()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in outer
File "<stdin>", line 4, in inner
UnboundLocalError: local variable 'x' referenced before assignment
>>>
問題1從內函數內部德爾X ons:
- 在第二個片段中,print語句如何創建局部變量。
- 如果它在內部函數中創建局部變量,爲什麼我不能刪除它。
有人可以幫我理解這一點。
快速搜索揭示了一個重複的問題,但它的答案不是很好。答案中的一些信息完全錯誤。我沒有投票結束。 – user2357112
從[Python文檔](http://docs.python.org/2/library/functions.html#locals):「自由變量由['locals()']返回(http://docs.python .org/2/library/functions.html#locals)在功能塊中調用時,不在類塊中調用。「 – user2357112
可能的重複[Python簡介範圍規則](http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules) –