Consider:
class Foo:
a = 1
def bar():
print(a)
I expected a
to be available to the method by scoping rules: local first, then enclosing, ...
The class Foo
creates a namespace and a scope, does it not?
bar
creates a scope; isn't it enclosed by the scope of the class? There is no a
defined in the scope of bar
, so I expected it to pick up the class variable from the enclosing scope.
Evidently I'm confused about namespaces and scopes. I've tried reading up on this, but haven't been able to find definitive clarification on this particular point (self.a
works, of course).
The class body is not a nestable scope, no. The Python Execution Model explicitly excludes it:
The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods
That's because the body of a class is executed to form the class attributes; see it as a function with locals, and the locals become the attributes of the new class object.
You can then access those attributes either on the class directly (Foo.a
) or via an instance (where attribute lookup falls through to the class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With