名称范围a
覆盖了整个函数f
,并且是纯静态的。说“打印语句有 50% 的可能性超出了范围”是完全不正确的。a
“。“不在范围内”并不是名称查找失败的唯一原因。
请注意从此函数中得到的错误:
>>> def foo():
... print a
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
NameError: global name 'a' is not defined
这与函数执行时出现的错误不同del a
. In my foo
, a
没有在本地范围内定义foo
,因此名称查找继续到全局范围,其中a
也没有找到,所以我们得到一个例外,即没有全局的a
.
你得到的错误清楚地表明Python知道这个名字a
是一个局部变量f
。然而它没有任何价值,因为你删除了它。 (通常这种情况只会发生,因为您在写入局部变量之前尝试读取它,这就是错误消息的措辞如此的原因)
另请注意这种情况:
a = 3
>>> def bar():
... a = 1
... del a
... print a
...
>>> bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in bar
UnboundLocalError: local variable 'a' referenced before assignment
Python 抱怨本地a
没有价值。如果a
根本不在本地范围内,它会查找a
在全球范围内发现了3
:
>>> a = 8
>>> def baz():
... print a
...
>>> baz()
8
这与您在以下情况下得到的行为不同:del
从全球范围来看的事情:
>>> a = 12
>>> del a
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
Here you get an exception as if a
had never existed. The reason for the difference is because the local scope of a function is static. If a function contains an assignment to a name, then that name is locally scoped over the entirety of the function's body1. Even before the first assignment, or after you've used del
to get rid of it, lookup of that name in that function will try to get the value of the local variable.
1 Unless the name has been declared global
or nonlocal
.