根据 python reference manual
我们有
When a name is not found at all, a NameError exception is raised. If the name refers to a local variable that has not been bound, a UnboundLocalError exception is raised. UnboundLocalError is a subclass of NameError.
我不明白什么时候
UnboundLocalError
被抛出?因为Python lacks declarations and allows name binding operations to occur anywhere within a code block.
那么我们如何才能声明一个变量,而不是初始化她呢?
最佳答案
您可以在没有分配的情况下引用名称:
>>> foobar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'foobar' is not defined
这里
foobar
被提及,但从未被分配到。这引发了 NameError
因为这个名字从未被绑定(bind)。更巧妙的是,这里没有发生分配,因为执行的行永远不会运行:
>>> def foo():
... if False:
... spam = 'eggs'
... print spam
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in foo
UnboundLocalError: local variable 'spam' referenced before assignment
因为
spam = 'eggs'
永远不会被执行,print spam
引发 UnboudLocalError
.请注意,Python 中没有任何地方声明过名称。您绑定(bind)或不绑定(bind),声明不是语言的一部分。
相反,绑定(bind)用于确定名称的范围;绑定(bind)操作包括赋值,用于
for
的名称循环、函数参数、导入语句、将捕获的异常保存在 except
中的名称子句,with
中的上下文管理器的名称声明所有绑定(bind)名称。如果名称绑定(bind)在范围内(例如在函数中),则它是本地名称,除非您使用
global
语句(或 Python 3 中的 nonlocal
语句)来显式地将名称标记为全局(或闭包)。所以下面是一个错误:
>>> foo = None
>>> def bar():
... if False:
... foo = 'spam'
... print foo
...
>>> bar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in bar
UnboundLocalError: local variable 'foo' referenced before assignment
因为
foo
被绑定(bind)在 bar
的某处功能范围。但是如果你标记 foo
作为一个全局函数,该函数有效:>>> foo = None
>>> def bar():
... global foo
... if False:
... foo = 'spam'
... print foo
...
>>> bar()
None
因为现在 Python 编译器知道你想要
foo
而是成为一个全局性的。这些都记录在 Naming and Binding section Python 引用文档。
关于python - 未绑定(bind)的变量和名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22101836/