为什么无法从方法访问 class 变量?

Why is a class variable not accessible from a method?

考虑:

class Foo:
    a = 1
    def bar():
        print(a)

我希望 a 可以通过范围规则对方法可用:首先是本地,然后是封闭,...

class Foo 创建了一个命名空间和一个作用域,不是吗?

bar 创建一个范围;不是在class的范围内吗? bar 的范围内没有定义 a,所以我希望它从封闭范围中获取 class 变量。

显然我对名称空间和范围感到困惑。我已经尝试阅读此内容,但未能找到关于这一特定点的明确说明(当然,self.a 有效)。

class 主体不是可嵌套范围,不是。 Python Execution Model 明确排除它:

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

那是因为class的body被执行形成了class的属性;把它看成一个带有局部变量的函数,局部变量成为新 class 对象的属性。

然后您可以在 class 上直接访问这些属性 (Foo.a) 或通过一个实例(其中属性查找落入 class)。

class Foo:
    def __init__(self):
        self.a = 1

    def bar(self):
        print(self.a)

通过使用__init__(),您将能够将变量传递给其他函数。