gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:15:07 26 4
gpt4 key购买 nike

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

非常感谢。

class test:
MATRIX = []

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

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

test.fun1()
print test.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

关于python - 如何将全局变量传递给另一个函数调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10493934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com