Python变量命名/绑定(bind)混淆

标签 python variables binding python-2.7 scope

我是 Python 开发的新手,在阅读语言文档时,我遇到了这样一行:

It is illegal to unbind a name that is referenced by an enclosing scope; the compiler will report a SyntaxError.

所以在学习练习中,我试图在交互式 shell 中创建此错误,但我一直无法找到这样做的方法。我使用的是 Python v2.7.3,所以使用 nonlocal 关键字

def outer():
  a=5
  def inner():
     nonlocal a
     print(a)
     del a

不是一个选项,并且在不使用 nonlocal 的情况下,当 Python 在 inner 函数中看到 del a 时,它会将其解释为本地未绑定(bind)的变量并抛出 UnboundLocalError 异常。

显然,对于全局变量,此规则有一个异常(exception),那么我如何创建一种情况,让我“非法”解除绑定(bind)一个被封闭范围引用的变量名?

最佳答案

删除必须发生在外部范围内:

>>> def foo():
...     a = 5
...     def bar():
...         return a
...     del a
... 
SyntaxError: can not delete variable 'a' referenced in nested scope

Python 3 中删除了编译时限制:

$ python3.3
Python 3.3.0 (default, Sep 29 2012, 08:16:08) 
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
...     a = 5
...     def bar():
...         return a
...     del a
...     return bar
... 
>>>

相反,当您尝试引用 a 时会引发 NameError:

>>> foo()()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in bar
NameError: free variable 'a' referenced before assignment in enclosing scope

我很想在这里提交文档错误。对于 Python 2,文档具有误导性;它正在删除在触发编译时错误的嵌套范围内使用的变量,并且在 Python 3 中根本不再引发错误。

关于Python变量命名/绑定(bind)混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15342545/

相关文章:

除非我重新创建整个列表,否则 WPF 绑定(bind)不会更新?

wpf - 内部控件和 View 模型之间的 UserControl 属性 "relay";感觉/工作不正常

python - 使用 OpenCV 从扫描的纸张中提取精确区域?

python - 根据 Python 中的其他值创建一个简短的唯一 ID?

C静态变量不更新

php - 帮助我了解如何在 PHP 中使用 $this

variables - 将 terraform 变量值从项目文件夹中的 .tfvars 文件传递​​到模块

python - 如何重新排列/重新排序 python 数据框中的行和列?

python - 使用 scipy 最小化二参数函数时的性能问题

WPF MVVM ListBox/ComboBox ItemsSource 不会从 ViewModel 更新 UI