簡體   English   中英

Python中非本地語句的語法錯誤

[英]syntax error on nonlocal statement in Python

我想測試在問題的答案中指定的使用非本地語句的示例:

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; 這是該語言的一種新增加

在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)
... 

非本地語句中列出的名稱不得與本地范圍內的現有綁定沖突。

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