在 Python 函数外声明全局变量

Declaring Global Variables in Python Outside of Functions

如果之前有人问过这个问题,请原谅我,但我不明白为什么这不起作用。为了记录,我已经用谷歌搜索了几个小时。 我不断收到全局变量错误。我这样声明我的全局变量:

###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] 复制到表面上),

如果您知道其他方法,请告诉我。我以前用 JASS 编码(这就是为什么我有一种时髦的方式来声明全局变量),我不知道还有什么方法可以让所有函数都可以访问列表。

非常感谢! -扎克

为了使用全局变量,您实际上需要在您的方法中明确设置它。这是一个应该对您有所帮助的示例:

glb = "I am global"

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

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

除了全局关键字外,您的变量名也需要匹配。您定义 global_AB 然后仅引用 AB.