我想测试使用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
)。
答案 0 :(得分:20)
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)
...
答案 1 :(得分:0)
非本地语句中列出的名称不得与本地范围中的预先存在的绑定冲突。
https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement
def outer():
x = 1
def inner():
nonlocal x
y = 2
x = y
print("inner: ", x)
inner()
print("outer: ", x)
def outer():
x = 1
def inner():
nonlocal x
y = 2
x = y
print("inner: ", x)
inner()
print("outer: ", x)