TL; DR 类在定义的时候是有作用域的,这个作用域内的变量只能在 class 块内访问,而不能在类的方法(函数)中访问。
这种问题当然应该是去看 Language Reference 啦
Python 3:
https://docs.python.org/3/reference/executionmodel.html#naming-and-binding> The following constructs bind names: formal parameters to functions, import statements, class and function definitions (these bind the class or function name in the defining block) ...
然后
> 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.