如何将全局变量传递给另一个函数调用的函数

2024-06-17 13:21:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的例子中,我想找出是什么导致了 ^{{cd2>执行时。在

非常感谢。在

class test:
    MATRIX = []

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

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

test.fun1()    
print test.MATRIX

Tags: testdefglobalmatrixclass例子printappend
2条回答

错误"NameError: global name 'MATRIX' is not defined"是因为代码中没有名为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
# >>> []

您的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

相关问题 更多 >