Python NameError:名称'N'未定义[重复]

为什么在使用类变量时Python(3.8)会抛出NameError?以下工作正常,

class Tester(object):
    # Number of measurements
    N = 6
    temp = [ 0. for x in range(N) ]

但是,当我尝试如下使用它时,它给出了NameError。

class Tester(object):
    # Number of measurements
    N = 6
    temp = [[ 0. for x in range(N) ] for y in range(N) ]

It seems to be happening for the first N. So something like temp = [[ 0. for x in range(6) ] for y in range(N) ] works fine.

When I replace N by Tester.N, it gives NameError for Tester, which makes sense since the class is not defined.

如何定义二维列表的温度?

评论
3、2、1
3、2、1

我不确定为什么您的方法行不通。如果将其添加到init中,它将起作用:

class Tester(object):

    def __init__(self):
        # Number of measurements
        N = 6
        temp = [[ 0. for x in range(N) ] for y in range(N) ]
        print(temp)

tester = Tester()
点赞
评论