在函数之外声明Python中的全局变量

时间:2015-10-06 01:28:44

标签: python pygame global-variables global declare

请原谅我,如果以前曾经问过,但我无法弄清楚为什么这不起作用。我用Google搜索了几个小时,以备记录。 我不断收到全局变量错误。我声明我的全局变量:

###Sprites###
global_AB = []
global_AM = []
global_AD = []
global_BB = []
global_CO = []
global_DK = []
global_FB = []
global_O = []
global_R = []
global_SS = []
global_S = []
global_WU = []

但是当我在一个函数中访问它时(在此函数设置之后)

#Loads all of the sprites and backgrounds, I recommend you close this if looking at the code.
def loadImages():
    for i in range(0, (len(spriteNames) - 1)):
        for z in range(0, numSprites[i]):
            if i == 0:
                AB.append(pygame.image.load(spriteNames[i] + str(z) + ".png_scaled.png"))
            elif i == 1:
                AM.append(pygame.image.load(spriteNames[i] + str(z) + ".png_scaled.png"))
            elif i == 2:
                AD.append(pygame.image.load(spriteNames[i] + str(z) + ".png_scaled.png"))
           ... 8 more of these

当通过blit图像访问时,我得到一个错误,说它没有定义(我试图将AB [0] blit到表面上),

如果您知道其他方式,请告诉我。我以前在JASS中编码(这就是为什么我有一种声明全局变量的时髦方式),而且我不知道如何保持列表能够在所有函数中被访问。

非常感谢! - 扎克

2 个答案:

答案 0 :(得分:2)

要使用全局,您需要在方法中实际显式设置它。以下是一个可以帮助您的示例:

glb = "I am global"

def foo():
    global glb
    glb = "I changed you mr. global"

foo()
# Outputs:  I changed you mr. global
print(glb) 

答案 1 :(得分:1)

除了global关键字,您的变量名称需要匹配。您定义global_AB,然后仅引用AB

相关问题