我想测试在this 上的答案中指定的非本地语句的使用示例。问题:
def outer():
x = 1
def inner():
nonlocal x
x = 2
print("inner:", x)
inner()
print("outer:", x)
但是当我尝试加载这段代码时,我总是会遇到语法错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "t.py", line 4
nonlocal x
^
SyntaxError: invalid syntax
有谁知道我在这里做错了什么(我使用的每个示例都有语法错误,包含 nonlocal
)。
nonlocal
仅适用于 Python 3;这是一个new addition to the language .
在 Python 2 中它会引发语法错误; python 将 nonlocal
视为表达式而不是语句的一部分。
当您实际使用正确的 Python 版本时,这个具体示例工作得很好:
$ 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 outer():
... x = 1
... def inner():
... nonlocal x
... x = 2
... print("inner:", x)
... inner()
... print("outer:", x)
...