SyntaxError nonlocal python in a method defenition
Question:
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
. 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.
Answers:
What you’re doing is creating a class
which has a class attribute a
, with a default value of 42
. You can refer to that attribute by A.a
. If you want to use it within the class, use self.a
.
Class scope are handled in a special way by Python: When looking for names in ecnlosing scopes, class scopes are skipped.
To access a name from the class scope either use self.a
to look up via the instance or A.a
to look up via the class.
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.
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
. 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.
What you’re doing is creating a class
which has a class attribute a
, with a default value of 42
. You can refer to that attribute by A.a
. If you want to use it within the class, use self.a
.
Class scope are handled in a special way by Python: When looking for names in ecnlosing scopes, class scopes are skipped.
To access a name from the class scope either use self.a
to look up via the instance or A.a
to look up via the class.
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.