简体   繁体   English

Python中非本地语句的语法错误

[英]syntax error on nonlocal statement in Python

I would like to test the example of the use of the nonlocal statement specified in the answer on this question: 我想测试在问题的答案中指定的使用非本地语句的示例:

def outer():
   x = 1
   def inner():
       nonlocal x
       x = 2
       print("inner:", x)
   inner()
   print("outer:", x)

but when I try to load this code, I always get a syntax error: 但是当我尝试加载此代码时,总是会出现语法错误:

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
  File "t.py", line 4
    nonlocal x
             ^
SyntaxError: invalid syntax

Does anybody know what I am doing wrong here (I get the syntax error for every example that I use, containing nonlocal ). 有人知道我在这里做错了吗(我使用的每个示例都包含nonlocal的语法错误。)

nonlocal only works in Python 3; nonlocal仅适用于Python 3; it is a new addition to the language . 这是该语言的一种新增加

In Python 2 it'll raise a syntax error; 在Python 2中,它将引发语法错误; python sees nonlocal as part of an expression instead of a statement. python将nonlocal视为表达式的一部分,而不是语句。

This specific example works just fine when you actually use the correct Python version: 当您实际使用正确的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)
... 

Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope. 非本地语句中列出的名称不得与本地范围内的现有绑定冲突。

https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement 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)
>>> outer() inner: 2 outer: 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM