简体   繁体   English

方法defenition中的SyntaxError nonlocal python

[英]SyntaxError nonlocal python in a method defenition

I'm typing in an interactive mode the following code: 我正在以交互模式键入以下代码:

class A:
    a=42
    def foo():
        nonlocal a

but I've a SyntaxError: no binding for nonlocal 'a' found . 但我有一个SyntaxError: no binding for nonlocal 'a' found But I'm expected that the result of resolution nonlocal a will be 42, because the nearest enclosing scope for this method is a class block. 但我预计解析nonlocal a的结果将是42,因为此方法的最近封闭范围是一个类块。

Class scope are handled in a special way by Python: When looking for names in ecnlosing scopes, class scopes are skipped. 类范围由Python以特殊方式处理:在ecnlosing范围中查找名称时,将跳过类范围。

To access a name from the class scope either use self.a to look up via the instance or Aa to look up via the class. 要从类范围访问名称,请使用self.a通过实例查找,或使用Aa通过类查找。

See The scope of names defined in class block doesn't extend to the methods' blocks. 请参见类块中定义的名称范围不会扩展到方法的块。 Why is that? 这是为什么? for a rationale for this behaviour. 了解这种行为的理由。

What you're doing is creating a class which has a class attribute a , with a default value of 42 . 你在做什么是创建一个class具有类属性的a ,用默认值42 You can refer to that attribute by Aa . 您可以通过Aa引用该属性。 If you want to use it within the class, use self.a . 如果要在类中使用它,请使用self.a

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

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