Skip to main content
 首页 » 编程设计

python之为什么这段 Python 代码会出现名称错误

2024年10月24日1698°冷暖

<分区>

我想要一个类的所有实例共享和访问的属性。

示例代码:

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

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

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