我正在以交互模式键入以下代码:
class A:
a=42
def foo():
nonlocal a
但我有SyntaxError: no binding for nonlocal 'a' found
。但我希望分辨率nonlocal a
的结果为42,因为此方法最近的封闭范围是一个类块。
答案 0 :(得分:4)
类范围由Python以特殊方式处理:在ecnlosing范围中查找名称时,将跳过类范围。
要从类范围访问名称,请使用self.a
通过实例查找,或使用A.a
通过课程查找。
请参阅The scope of names defined in class block doesn't extend to the methods' blocks. Why is that?了解此行为的基本原理。
答案 1 :(得分:0)
您正在做的是创建一个class
,其类属性为a
,默认值为42
。您可以通过A.a
引用该属性。如果要在课程中使用它,请使用self.a
。