问题是在这篇文章的末尾。如何打印语句创建一个局部变量
第一个片段:空局部变量字典。
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) –