为什么此 Python 代码会出现名称错误?

Why does this Python code get the name error?

我想要一个 class.

的所有实例共享和访问的属性

示例代码:

class Test:

    code = [ 1, 2, 3, 5, 6, 7, 8, 9, 10]
    code2d = [ [ code[j*3 + i] for i in range(3) ] for j in range(3) ]

    def __init__(self):
        pass

但是,我得到错误:

NameError: name 'code' is not defined

如果我将带有 codecode2d 的行放入 init 方法中,一切正常。

为什么这段代码会抛出错误?

code 是一个 class 变量,因此在访问它时您需要调用 - Test.code ,您不能使用 code 访问它们。

此外,即使您使用 Test.code 访问它们,它仍然不起作用,因为 class 变量的值(默认值)是在 class 是正在定义,因此当您尝试访问 Test.code 时,您将无法访问 Test,因为它尚未创建。例子 -

>>> class Test:
...     code = [ 1, 2, 3, 5, 6, 7, 8, 9, 10]
...     code2d = [ [ Test.code[j*3 + i] for i in range(3) ] for j in range(3) ]
...     def __init__(self):
...         pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in Test
  File "<stdin>", line 3, in <listcomp>
  File "<stdin>", line 3, in <listcomp>
NameError: name 'Test' is not defined

我猜当你将它们放在 __init__() 中时,你将它们作为 -

class 测试:

def __init__(self):
    code = [ 1, 2, 3, 5, 6, 7, 8, 9, 10]
    code2d = [ [ code[j*3 + i] for i in range(3) ] for j in range(3) ]

这行得通,因为 code 这里是一个 local variable,因此可以被 __init__() 方法中的其他局部变量访问,尽管它们在这个方法之外是不可访问的功能。


也许,你不需要它们作为 class 变量 ,如果你想要 codecode2d 的所有实例class(class 的对象),您应该创建实例变量为-

>>> class Test:
...     def __init__(self):
...         self.code = [ 1, 2, 3, 5, 6, 7, 8, 9, 10]
...         self.code2d = [ [ self.code[j*3 + i] for i in range(3) ] for j in range(3) ]

如果您真的希望 codecode2d 成为 class 变量,一种方法是在 class 之外定义 code2d Test ,示例 -

class Test:
    code = [ 1, 2, 3, 5, 6, 7, 8, 9, 10]
    def __init__(self):
        pass


Test.code2d = [ [ Test.code[j*3 + i] for i in range(3) ] for j in range(3) ]