This might seem weird (and it is), but you don't get a closure over class
, it's only over def
. The "enclosing" scope referred to in LEGB is just talking about function definitions; class blocks don't count here.
That strange behaviour is an artifact of the way in which classes were added to Python historically. The class scope is not a real scope. Python didn't always have classes, and the spooky "intermediate scope" just exists during the class definition: internally, the code under the class body is more or less just run through exec
under a temporary scope with the result being assigned to the class name. This was a very simple "bolt-on" approach to get OOP into the language, at the time, and it's also the reason why Python has the explicit self
thing as an intentional language design choice.
To access the a_var
from the "class scope" from inside a method, you will have to use attribute access via either self.a_var
or Test.a_var
. Both should work. You may also access it directly at the class level, during the class definition, but since you are still inside the temporary scope that is just another example of a local access (LEGB).
This is documented (albeit not particularly clearly) under the execution model section.
Class definition blocks and arguments to exec() and eval() are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition becomes the attribute dictionary of the class. 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 – this includes comprehensions and generator expressions since they are implemented using a function scope.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…