Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python class variable accessible from class method?

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

like image 282
garyp Avatar asked Mar 17 '23 06:03

garyp


1 Answers

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

like image 144
Martijn Pieters Avatar answered Apr 01 '23 10:04

Martijn Pieters