1

给出下面的例子,我想弄清楚是什么原因导致 "NameError: global name 'MATRIX' is not defined"执行时出现异常test.fun1()

非常感谢。

class test:
    MATRIX = []

    @staticmethod        
    def fun1():
        global MATRIX
        test.fun2(MATRIX)

    @staticmethod
    def fun2(MATRIX):
        MATRIX.append(2)

test.fun1()    
print test.MATRIX
4

2 回答 2

3

MATRIX不是全局的,它是一个类属性,试试这样:

class test:
    MATRIX = []

    @classmethod     # Note classmethod, not staticmethod   
    def fun1(cls):   # cls will be test here
        test.fun2(cls.MATRIX)

    @staticmethod
    def fun2(MATRIX):
        MATRIX.append(2)

test.fun1()    
print test.MATRIX
于 2012-05-08T06:50:38.943 回答
2

该错误"NameError: global name 'MATRIX' is not defined"是由于您的代码中没有名为 MATRIX 的全局变量引起的。

在您的代码中MATRIX不是全局变量,而是类属性。全局变量将像这样使用:

MATRIX = []

class test:

    @staticmethod
    def fun1():
        test.fun2(MATRIX)

    @staticmethod
    def fun2(l):
        l.append(2)

    @staticmethod
    def reset():
        global MATRIX
        MATRIX = []

test.fun1()
print MATRIX
# >>> [2]
test.fun1()
print MATRIX
# >>> [2, 2]
test.reset()
print MATRIX
# >>> []
于 2012-05-08T06:57:48.453 回答